NoLAstNamE's avatar

whereRelation select only the needed column

In Laravel, when using whereRelation from my understanding, you don't need to add with() because you're already using it inside whereRelation.

Here's the whereRelation code:

Task::query()
->whereRelation(
    'user', 'name', 'like', "%{$request->search}%"
)
->get();

But what if I only want to select what I need in that relationship? e.g. I only want to select the user's name because that's what I'm only filtering?

Here's the with with only selecting the name:

Task::query()
->with(
    'user:name'
)
->get();
0 likes
1 reply
LaryAI's avatar
Level 58

You can use the select method on the whereRelation method to select only the needed column. Here's an example:

Task::query()
    ->whereRelation(
        'user', function ($query) use ($request) {
            $query->select('name')->where('name', 'like', "%{$request->search}%");
        }
    )
    ->get();

In this example, we're passing a closure to the whereRelation method, which allows us to use the select method to select only the name column from the user relationship. We're also using the where method to filter the results based on the search term.

Note that we're using the use keyword to pass the $request variable to the closure. This is necessary because closures have their own scope and don't inherit variables from the parent scope.

1 like

Please or to participate in this conversation.