How Do I Get API Resource Responses In Laravel Framework

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 Do I Get API Resource Responses In Laravel Framework

API Resource Responses
 

To get Resource Respones first we need to create api resource and then resources may be returned directly from routes and controllers:

To Create Resources visit our Bajarangisoft site.


Example(1)
after creating resource open web.php file and you can return resource data in route as below 

 

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

Route::get('/user', function () {
    return new UserResource(User::find(1));
});

Or you can also return resource data from controller 
for example(1)

1.Create route in web.php as below code implemented 

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


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

php artisan make:controller demoController -mcr


3.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 UserCollection(User::find(1));
    }
}


However, sometimes you may need to customize the outgoing HTTP response before it is sent to the client. There are two ways to accomplish this. First, you may chain the response method onto the resource. This method will return an Illuminate\Http\JsonResponse instance, allowing you full control of the response's headers:

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

Route::get('/user', function () {
    return (new UserResource(User::find(1)))
        ->response()
        ->header('X-Value', 'True');
});


Alternatively, you may define a withResponse method within the resource itself. This method will be called when the resource is returned as the outermost resource in a 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,
        ];
    }

    /**
     * Customize the outgoing response for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Http\Response  $response
     * @return void
     */
    public function withResponse($request, $response)
    {
        $response->header('X-Value', 'True');
    }
}

Related Post