Support the ongoing development of Laravel.io →
Database Eloquent

Is it possibly to make a WHERE query on a eager loaded relationship?

Say my users table has a name, and I'd like to filter profiles by the name of the user

Users

-id

-name

With a join:

$query = Profile::leftJoin('users', 'users.id', '=', 'profiles.user_id')
    ->with('rank', 'game', 'roles', 'gamemodes', 'characters')
    ->where(function($query)
    {
      if(\Request::get('name'))
        $query->where('name', 'LIKE', '%' . \Request::get('name') . '%');
    })
    ->get();

Into something like:

$query = Profile::with('user', 'rank', 'game', 'roles', 'gamemodes', 'characters')
    ->where(function($query)
    {
      if(\Request::get('name'))
        $query->where('user.name', 'LIKE', '%' . \Request::get('name') . '%');
    })
    ->get();

Just wanted to know if this is possible, whether it's better or not, I don't know. It would make it easier as a lot of tables I want to join have the same column names, and I'd have to make a lot of aliases.

Cheers

Last updated 3 years ago.
0

Actually, I think I solved it. I was looking in the wrong part of the documentation.

This seems to work:

$query = Profile::with('user', 'rank', 'game', 'roles', 'gamemodes', 'characters')
    ->whereHas('user', function($query)
    {
      if(\Request::get('name'))
        $query->where('name', 'LIKE', '%' . \Request::get('name') . '%');
    })
    ->get();

Will come back, if this isn't the case after all.

0

Bonus Update:

I just realized that if I getXAttribute() I can then append this on my object and don't have to use ->with(). Which allows me to use the built in pagination

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.