prakashchhetri
prakashchhetri

Reputation: 1816

Complex Eloquent Relation Laravel

I have a simple ticketing system. Lets say, I am fetching a ticket, and all the relations to it. A ticket can have multiple replies, as well as multiple attachments.

$ticket = Ticket::with('replies')
                    ->with('attachments')
                    ->find($id); 

Similarly every reply will have a user_id, and hence fetch the details for the user.

This is where the trick is.

I cannot think of a way to do that other than looping though each of the replies and manually fetching user details for each reply.

But I believe there is a better way.

Upvotes: 0

Views: 56

Answers (2)

Yogendra
Yogendra

Reputation: 1300

Add belongsTo relation with user table in your Reply model.

$ticket = Ticket::with('replies.user', 'attachments')->find($id);

And if you want to show list of all replies, you can use

$replies = Reply::with('user')->get();

Upvotes: 2

Imran Khan
Imran Khan

Reputation: 321

You can modify your query as below with a new relation in replies model, let it be userDetails

$ticket = Ticket::find($id)
->with([
    'replies',
    'replies.userDetails',
    'attachments'
]);

Upvotes: 1

Related Questions