Zuruck
Zuruck

Reputation: 5

Add additional data to paginated resource laravel

This is the response of a GET request in an API with paginated data:

{
"current_page": 1,
"data": [
    {
        "id": 11,
        "user_id": 1,
        "text": "kek",
        "path": "public/gifs/mfNEs0XOK7X3ovIYdMwW67lemI4oRAos0ufxNeBm.gif",
        "created_at": "2020-09-18T01:32:47.000000Z",
        "updated_at": "2020-09-18T01:32:47.000000Z"
    },
    {
        "id": 12,
        "user_id": 1,
        "text": "kek",
        "path": "public/gifs/bFwa5My7NlkdtTFiqn6FXLzpcbaL9703phDEYQ5i.gif",
        "created_at": "2020-09-18T01:38:55.000000Z",
        "updated_at": "2020-09-18T01:38:55.000000Z"
    }
],
// ... rest of the pagination data
}

I need to insert a tags field in each of the models, which values comes from a Many To Many relationship.

Do I need to iterate the collection and insert each value manually or does laravel have a built in method for that?

Current function:

public function index()
{
    $expressions = $this->expression->paginate(20);
    
    return response()->json($expressions);
}

Upvotes: 0

Views: 192

Answers (1)

lagbox
lagbox

Reputation: 50491

Load the relationship so it is part of the serialized output of the Model:

$expressions = $this->expression->with('tags')->paginate(20);

Assuming $this->expression is an instance of your Model.

"When an Eloquent model is converted to JSON, its loaded relationships will automatically be included as attributes on the JSON object."

Laravel 7.x Docs - Eloquent - Relationships - Serialization - Serializing to JSON

Laravel 7.x Docs - Eloquent - Relationships - Eager Loading with

Upvotes: 2

Related Questions