Search code examples
laraveleloquenteloquent-relationship

How to use Where clause on laravel relation?


For each of the data in Post table , I have to check whether the field name of the relation user has value equal to $request->name and output the posts matching this condition . But The below code (Method 1) returns null from user relation.How can i fix this?

Controller

Method 1:

$post=Post::where('status',1)
 ->with([
'user' => function ($query) use ($request) {
$query->where('name',$request->name);
$query->select('name','age');
}
])
->latest();

Method 2 :

$p = Post::where('status', 1)
                ->with('user')
         ->whereHas('user', function ($query) use ($request) {
                        $query->select('age', 'name');
                    }
                )
                ->get();
if ($request->name)
             {
                $p->user->where('name', $request->name); 
             }  

Method 2 returns error Exception: Property [user] does not exist on the Eloquent builder instance.

Post Model

public function user()
    {
        return $this->belongsTo(
            'App\Models\User',
            'user_id',
            'id'
        );
    }

Solution

  • You can use WhereHas in your query like this :

    $user_name=$request->name;
    $p = Post::where('status', 1)
                    ->with('user')
                    ->WhereHas('user', function ($query) use ($user_name) {
                        $query->where('user.name',$user_name);
                     })->get();
    

    So you get the posts where the user of this post has the given name.