属性 [id] 在 Laravel 5.5 中不存在

Property [id] does not exist in Laravel 5.5

为什么我不断收到此错误:属性 [id] 在此集合实例上不存在。

我的方法:

public function modes()
{
    $modes = Genre::limit($this->limit)->get();


    return new GenresResource($modes);
}

我的资源

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

M 型号

class Genre extends Model {

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'genres';

protected $guarded = ['id'];

}

据我了解 - 您的 $thisCollection,而不是 Model。显然该集合没有属性 idname.

您需要更改控制器方法以指示它正在接收一个集合,而不是单个模型。

$modes = Genre::limit($this->limit)->get();

return GenresResource::collect($modes);

通常您会希望为您的资源指定一个单数名称,因此您可能也想考虑将其命名为 GenreResource