What Are The Resource Collection In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.

What Are The Resource Collection In Laravel With Example

Resource Collections

If you are returning a collection of resources or a paginated response, you may use the collection method when creating the resource instance in your route or controller:

So, for example


Create user resource using below command 

php artisan make:resource User

Open app\Resources\User.php file to implement below code

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}


Create Route in Web.php file as below

Route::get('/fulluserdata ', 'demoController@fulluserdata')->name('fulluserdata');
 

Create demoController and implement code to get all data from user table

php artisan make:controller demoController -mcr


Open demoController.php in app\Http\Controller folder and implement code as below

<?php

namespace App\Http\Controllers;
use App\Http\Resources\User as UserResource;
use App\User;

class demoController extends AppBaseController
{
    public function Users()
    {
        return new UserResource(User::find(1));
    }
}
 

Note that this does not allow any addition of meta data that may need to be returned with the collection. If you would like to customize the resource collection response, you may create a dedicated resource to represent the collection:

Create UserCollection resource using below command 

php artisan make:resource UserCollection


Once the resource collection class has been generated, you may easily define any meta data that should be included with the response:

Open app\Resources\UserCollection.php file to implement below code
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}


Create Route in Web.php file as below
Route::get('/Users ', 'demoController@Users')->name('Users');


Open demoController.php in app\Http\Controller folder and implement code as below
<?php

namespace App\Http\Controllers;
use App\User;
use App\Http\Resources\UserCollection;

class demoController extends AppBaseController
{
    public function Users()
    {
        return new UserCollection(User::all());
    }
}
 

Preserving Collection Keys

When returning a resource collection from a route, Laravel resets the collection's keys so that they are in simple numerical order. However, you may add a preserveKeys property to your resource class indicating if collection keys should be preserved:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * Indicates if the resource's collection keys should be preserved.
     *
     * @var bool
     */
    public $preserveKeys = true;
}
 

When the preserveKeys property is set to true, collection keys will be preserved:

use App\Http\Resources\User as UserResource;
use App\User;

Route::get('/user', function () {
return UserResource::collection(User::all()->keyBy->id);
});
 

Customizing The Underlying Resource Class
 

Typically, the $this->collection property of a resource collection is automatically populated with the result of mapping each item of the collection to its singular resource class. The singular resource class is assumed to be the collection's class name without the trailing Collection string.

For example, UserCollection will attempt to map the given user instances into the User resource. To customize this behavior, you may override the $collects property of your resource collection:
 

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * The resource that this resource collects.
     *
     * @var string
     */
    public $collects = 'App\Http\Resources\Member';
}

Related Post