Relations in model events

Posted 1 year ago by Cinek

Hi, I'm testing an Eloquent model events. I have an listener which listen a user model retrieving.

protected $dispatchesEvents = [
        'retrieved' => UserEvent::class

I fetch all users in database with images:

$users = User::with('images')->get();

and i'd like to use this images in event listener:

$images = $user->images;

Problem is in the generated sql queries. Eloquent did 5 database queries:

select * from `users`;
select * from `images` where `images`.`user_id` = 1 and `images`.`user_id` is not null;
select * from `images` where `images`.`user_id` = 2 and `images`.`user_id` is not null;
select * from `images` where `images`.`user_id` = 3 and `images`.`user_id` is not null;
select * from `images` where `images`.`user_id` in (1, 2, 3);

Queries 2,3,4 are from event listener. It's possible to use images relation in user model event listener without additional queries?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.