3

我有简单的 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

我怎样才能使这项工作?

4

1 回答 1

14

你可以这样做

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
}
于 2018-07-01T18:01:56.017 回答