Search code examples
laravellaravel-5laravel-collection

How to use eloquent ->with method on collection


You may find the question stupid. I may not be doing the research well so I thought to ask it here. I would like to know how to use ->with on collection or what is its equivalent. Here is the code:

$theLastCommentOfThisPost = $post->comments->with('user')->sortByDesc('id')->first();

I would like to get something like this:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [id] => 19
            [commentable_type] => App\Post
            [commentable_id] => 123
            [comment] => totoototo
            [is_approved] => 1
            [user_id] => 1
            [created_at] => 2019-04-01
            [updated_at] => 2020-02-04
            [user] => App\User Object
                    (
                        [id] => 1
                        [name] => App\Post
                        [email] => [email protected]
                    )
        )

)

thanks


Solution

  • If you want to "load" relationships for a Collection of Models you would use the load method.

    $post->comments->load('user')->.....
    

    Though to not have to load all the comments to only get one you can do this with a query:

    $post->comments()->with('user')->latest()->first();
    

    Not really sure overall the data you need besides this one object.

    Laravel 5.8 Docs - Eloquent Collections - Available Methods - load