26
votes

I have an eloquent models as,

User : users(id, username, password, email, status)

Profile : profiles(id, user_id, first_name, last_name, gender, dob)

In the controller logic, I am eagerly loading the Profile model.

I can do this,

$user = User::with('Profile')->get();

or

$user = User::with('Profile')->where('status', '1')->get();

but how to do something like,

$user = User::with('Profile')->where('status', '1')->where('gender', 'Male')->get();
2

2 Answers

68
votes

That's where whereHas comes in handy:

$user = User::with('Profile')->where('status', 1)->whereHas('Profile', function($q){
    $q->where('gender', 'Male');
})->get();

Basically it adds the condition that the user needs to have a profile with gender = Male

17
votes

If you want to search multiple columns in relation model.

        $searchText = 'test text';
        Product::with('owner')->where(function($query) use ($searchText)
        {
            $query->where('product_name', 'LIKE', '%' . $searchText . '%');

            $columns = ['product_code', 'place_location', 'remark'];

            foreach ($columns as $column ) {
                $query->orWhere($column, 'LIKE', '%' . $searchText . '%');
            }

            $query->orWhereHas('owner', function($q) use ($searchText) {
                $q->where(function($q) use ($searchText) {
                    $q->where('name', 'LIKE', '%' . $searchText . '%');
                    $q->orWhere('company_name', 'LIKE', '%' . $searchText . '%');
                });
            });

        });