Search code examples
laravellaravel-query-builder

Laravel select * where id =(select id )


Using Laravel eloquent how do I make a query like this:

 select * from branches where user_id =(select id from users where name ='sara' )

Solution

  • Assuming that you have a user relationship in your Branch model you could use whereHas:

    $branches = Branch::whereHas('user', function ($query) {
    
        $query->where('name', 'sara');
    
    })->get();
    

    Update

    If you're using v8.57.0 or above, you can now use the whereRelation() method instead:

    Branch::whereRelation('user', 'name', 'sara')->get();