Search code examples
laravellaravel-resource

Laravel resource conditional return


I've got simple laravel resource:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'unread' => $this->unread,
            'details' => new EmployeeAddressResource($this->employeeAddress),
        ];
    }
}

This is working fine, now I want to make details conditional :

       'details' => $this
        ->when((auth()->user()->role == 'company'), function () {
               return new EmployeeAddressResource($this->employeeAddress);
                }),

and it works fine too, but how can I add other condition to return other resource? For exaple, if role is user i want to get resource: CompanyAddressResource

I tried this:

       'details' => $this
        ->when((auth()->user()->role == 'company'), function () {
                    return new EmployeeAddressResource($this->employeeAddress);
                })
        ->when((auth()->user()->role == 'user'), function () {
                    return new CompanyAddressResource($this->companyAddress);
                }),

but this is not working, when I'm logged as company it gives no details

How can I make this work?


Solution

  • You can do it like this

    public function toArray($request)
    {
        $arrayData = [
            'id' => $this->id,
            'unread' => $this->unread
        ];
    
        if(auth()->user()->role == 'company'){
            $arrayData['details'] = new EmployeeAddressResource($this->employeeAddress);
        }else {
            $arrayData['details'] = new CompanyAddressResource($this->companyAddress);
    
        }
    
        return $arrayData
    }