$cards = Card::query();
if (!empty($search) and strlen($search) >= 3) {
$cards->whereHas('user', function (Builder $query) use ($search) {
$query->where('email', 'like', '%' . $search . '%');
});
}
$cards = $cards->paginate(5)->withQueryString();
Jul 13, 2023
3
Level 3
Eloquent query [solved]
I have 3 tables
cards card_users users
Cards model class
public function cardUser()
{
return $this->belongsTo(CardUser::class);
}
CardUser model class
public function user()
{
return $this->belongsTo(User::class);
}
In Card controller and I need make a filter by typing an email and search cards by user accross CardUser model. CardUser model contains the user profile, the email is in users table, and this is related in CardUser table.
Class CardController extends Controller {
$cards = Card::query();
if (!empty($search) and strlen($search) >= 3 ) {
}
$cards = $cards->paginate(5)->withQueryString();
...
}
How can add a email filter using query builder?.
Level 3
Searching some more I found the way.
if (!empty($search) and strlen($search) >= 3 ) {
$cards->whereHas('cardUser.user', function ($query) use ($search) {
$query->where('email', 'like', "%$search%");
});
}
Please or to participate in this conversation.