Ресурс условного возврата Laravel
У меня есть простой ресурс Laravel:
<?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),
];
}
}
Это работает нормально, теперь я хочу сделать детали условными:
'details' => $this
->when((auth()->user()->role == 'company'), function () {
return new EmployeeAddressResource($this->employeeAddress);
}),
и это тоже отлично работает, но как я могу добавить другое условие, чтобы вернуть другой ресурс? Например, если роль user
я хочу получить ресурс: CompanyAddressResource
Я попробовал это:
'details' => $this
->when((auth()->user()->role == 'company'), function () {
return new EmployeeAddressResource($this->employeeAddress);
})
->when((auth()->user()->role == 'user'), function () {
return new CompanyAddressResource($this->companyAddress);
}),
но это не работает, когда я вошел как company
это не дает details
Как я могу сделать эту работу?
1 ответ
Решение
Вы можете сделать это так
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
}