lundi 4 juin 2018

Add more constructer parameter to resource collection

I am trying to make a general API Resource for a type of list in my project. The list will always have a name and type along with its associated data.

So far how I have it right now I have to create a collection for each list. What I am wondering is if there is a way to make one Collection where I can pass a type and name string with the data parameter So I can have one collection request instead of many.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserListCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'type' => 'User',
            'name' => 'User List',
            'data' => User::collection($this->collection)

        ];
    }
}

As you can see this is tightly coupled to the user model. I would like to make a collection class where I could call it like this.

new ListCollection($data,$name,$type);

Is there a way to accomplish what I am trying to do?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire