Home > Software design >  Laravel, query on joined table after join
Laravel, query on joined table after join

Time:01-11

The functionality: I'm displaying a list of responses (user is related to a response), and i want to be able filter by user name

I have an assignment response table with a user id in it

i am joining users to this table based on that id

i have a search filter for these responses

I want to be able to search by user name

Is it possible to do something like this;

$responses = AssignmentResponse::query()->where('assignment_id', '=', $request->assignment)
        ->with([
            'likes',
            'user'
        ]);

    //FILTERS
    if ($request->queryString) {
        $responses->where('user.name', 'LIKE', '%' . $request->queryString . '%');
    }

    return $responses->get();

CodePudding user response:

Simply alter the relationship with a callback:

return AssignmentResponse::where('assignment_id', $request->assignment)
    ->with('likes')
    ->when(
        $request->filled("queryString"),
        function ($q) use ($request) {
            $q->whereHas("user", fn ($q) => $q->where("name", "like", "%$request->queryString%"))
                ->with(["user" => fn ($q) => $q->where("name", "like", "%$request->queryString%")]);
        }
    )
    ->get()

Note both with() and whereHas() are used to ensure only matching values are returned. A conditional clause is used in place of your if statement.

  •  Tags:  
  • Related