Laravel - API Resources - 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:

    
    use Illuminate\Support\Facades\Auth;
    
    /**
     * 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,
            '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 before it is sent 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';
    }),