How To Do Resource Conditional Attributes In Laravel

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 Do Resource Conditional Attributes In Laravel

Conditional Attributes

Sometimes you may wish to only include an attribute in a resource response if a given condition is met.

For example, you may wish to only include a value if the current user is an "administrator". Laravel provides a variety of helper methods to assist you in this situation. The when method may be used to conditionally add an attribute to a resource response:



1.Open app\Http\Resources\User.php and implement code as below

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
class User extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */

    public static $wrap = 'user';

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'secret' => $this->when(Auth::user()->isAdmin(), 'secret-value'),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}


In this example, the secret key will only be returned in the final resource response if the authenticated user's isAdmin method returns true. If the method returns false, the secret key will be removed from the resource response entirely before it is sent back to the client. The when method allows you to expressively define your resources without resorting to conditional statements when building the array.

The when method also accepts a Closure as its second argument, allowing you to calculate the resulting value only if the given condition is true:

'secret' => $this->when(Auth::user()->isAdmin(), function () {
    return 'secret-value';
}),


2.Create route in web.php

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


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

php artisan make:controller demoController -mcr


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

<?php

namespace App\Http\Controllers;

App\Http\Requests;
use App\Http\Resources\User as UserResource;
use App\User;
class demoController extends AppBaseController
{
    public function Users()
    {
        return new UserResource(User::find(1));
    }
}


Merging Conditional Attributes

Sometimes you may have several attributes that should only be included in the resource response based on the same condition. In this case, you may use the mergeWhen method to include the attributes in the response only when the given condition is true:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
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,
            $this->mergeWhen(Auth::user()->isAdmin(), [
                'first-secret' => 'value',
                'second-secret' => 'value',
            ]),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}


Again, if the given condition is false, these attributes will be removed from the resource response entirely before it is sent to the client.

The mergeWhen method should not be used within arrays that mix string and numeric keys. Furthermore, it should not be used within arrays with numeric keys that are not ordered sequentially.

Related Post