Tommy Hoang
Tommy Hoang

Reputation: 355

Select User by Profile name in Laravel way

I have models User and Profile with hasOne relationship as following:

class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class, 'user_id');
    }
}

I want to select all users by full_name attribute of Profile in Laravel way. I have tried to this code but it return all the users in user table.

User::with(['profile' => function ($q) use ($request) {
    $q->where('last_name', 'LIKE', '%' . $request->input('name') . '%');
}]);

Any idea? Thanks so much.

Upvotes: 1

Views: 339

Answers (1)

pr1nc3
pr1nc3

Reputation: 8348

Try whereHas method like:

User::whereHas('profile', function($q) use($request) {
    $q->where('last_name', 'LIKE', '%' . $request->input('name') . '%');
});

Upvotes: 2

Related Questions