gpt4 book ai didi

Laravel 资源条件返回

转载 作者:行者123 更新时间:2023-12-02 09:11:53 27 4
gpt4 key购买 nike

我有简单的 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
我怎样才能使这项工作?

最佳答案

你可以这样做

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
}

关于Laravel 资源条件返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51125222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com