Laravel 资源条件返回

Posted

技术标签:

【中文标题】Laravel 资源条件返回【英文标题】:Laravel resource conditional return 【发布时间】:2018-12-10 00:50:40 【问题描述】:

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

【讨论】:

感谢这个例子,非常有帮助,而且不是很明显

以上是关于Laravel 资源条件返回的主要内容,如果未能解决你的问题,请参考以下文章

phpunit 测试资源 laravel 5.5 返回集合而不是 json

Laravel:控制器资源索引不返回视图或字符串

Laravel 返回自定义 api 资源

为啥 Laravel vendor:publish 返回“无法找到可发布的资源”?

Laravel API 资源集合从其他资源返回特定字段

如何在 laravel 5.5 中将数组作为 API 资源返回