How To Write Resource In Laravel Framework 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.

How To Write Resource In Laravel Framework With Example

Writing Resources

To Create Resources visit our Bajarangisoft site.

Resources are simple. They only need to transform a given model into an array. So, each resource contains a toArray method which translates your model's attributes into an API friendly array that can be returned to your users:

<?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,
        ];
    }
}


Once a resource has been defined, it may be returned directly from a route or controller as below:

Create route in web.php
Route::get('/fulluserdata ', 'demoController@fulluserdata')->name('fulluserdata');


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

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));
    }
}
 

Relationships

If you would like to include related resources in your response, you may add them to the array returned by your toArray method. In this example, we will use the Post resource's collection method to add the user's blog posts to the resource response:
 

<?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,
            'posts' => PostResource::collection($this->posts),//accessing data from post
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
 

Resource Collections

While resources translate a single model into an array, resource collections translate a collection of models into an array. It is not absolutely necessary to define a resource collection class for each one of your model types since all resources provide a collection method to generate an "ad-hoc" resource collection on the fly:
use App\Http\Resources\User as UserResource;
use App\User;

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


However, if you need to customize the meta data returned with the collection, it will be necessary to define a resource collection:

<?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',
            ],
        ];
    }
}


Like singular resources, resource collections may be returned directly from routes or controllers:

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

Route::get('/users', function () {
    return new UserCollection(User::all());
});

Related Post