Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Search relation including null in whereHas

I'm trying to find a way to search the relationship.

So, I have one to one relation (User and UserDetails, where some of the user can be without details).

So, the question is... how can I search Users by their details, but also Users without details must be included into the results.

Example: Table users: user_id, name, email - 1 John Doe [email protected] - 2 Richard Tim [email protected] - 3 Michael Bird [email protected]

Table user_details: ID, user_id, state - 1, 1, California - 2, 2, New York

and now... I want to get all users from California, and all users without state (In above case results should be John Doe and Michael Bird

Here is relation in User model:

public function details()
{
    return $this->belongsTo('App\UserDetails', 'user_id', 'user_id');
}

and search function is:

$users = $users->whereHas('details', function($query) use $state {
    $query->where('state', $state);
});

Keep in mind that I must to do that using instance of eloquent / query builder, I'm not able to use joins or raw queries.

In this case, I want to get all users from California and all non-related users, but the query returns/search only related users/user_details...

So, can someone to help me ? Thanks

UPDATE:

I'm trying like that:

$users = new User();
$users = $users->doesntHave('user_details')->orWhereHas('user_details', function($query) use($state) {
                $query->whereIn('state', $state);
            });
$users->where('created_at', '>=', $start_date);
$users->where('created_at', '<=', $end_date);
like image 529
Damjan Krstevski Avatar asked May 17 '17 16:05

Damjan Krstevski


1 Answers

You can use doesntHave in conjunction with orWhereHas to create the desired query:

User::doesntHave('details')->orWhereHas('details', function($query) {
    $query->where('state', '=', $state);
})->where('users.created_at', '>=', $start_date)
    ->where('users.created_at', '<=', $end_date)
    ->get();  
like image 185
Alex Harris Avatar answered Nov 04 '22 12:11

Alex Harris