【问题标题】:Laravel 8 - Property [name] does not exist on this collection instanceLaravel 8 - 此集合实例上不存在属性 [名称]
【发布时间】:2021-09-05 01:04:14
【问题描述】:

我正在尝试创建 Collection 以返回 Laravel 8 上 API 请求的特定字段。我的资源文件:

    public function toArray($request) {
        return [
            'name' => $this->name
        ];
    }

当我尝试获取所有用户时,我收到了这个错误:

Property [name] does not exist on this collection instance.

我的 api.php

    Route::get('/users', function () {
        return new UsersResource(User::all());
    });

我是否需要在模型中写一些东西才能让它工作?

【问题讨论】:

  • 模型是否在 $fillable 数组中包含名称?

标签: php laravel api collections resources


【解决方案1】:

从JsonResource扩展UserResource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;


class UsersResource extends JsonResource
{
  
    public function toArray($request)
    {

        return [
            'name' => $this->name
        ];
    }
}

并且 那么您可以执行以下操作

Route::get('/users', function () {
    return UsersResource::collection(User::all());
});

【讨论】:

    【解决方案2】:

    将您的路线代码更改为

    Route::get('/users', function () {
        return UsersResource::collection(User::all());
    });
    

    参见文档https://laravel.com/docs/8.x/eloquent-resources#resource-collections

    【讨论】:

    • 我得到了同样的结果。我清除了路由缓存
    猜你喜欢
    • 2021-07-02
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2020-07-11
    相关资源
    最近更新 更多