Laravel 8 - 属性 [name] 在此集合实例上不存在

Laravel 8 - Property [name] does not exist on this collection instance

我正在尝试为 Laravel 8 的 API 请求的 return 特定字段创建集合。我的资源文件:

    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());
    });

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

将您的路线代码更改为

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

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

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());
});