调用数组的成员函数 toBase()
Call to a member function toBase() on array
我正在尝试使用资源收集,但收到此错误“调用数组上的成员函数 toBase()”
The following code is in my resource :
class dataCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection
];
}
}
and here is code from the controller:
$projects = count(Project::all());
$services = count(Service::all());
$users = count(User::all());
$technologies = count(Technology::all());
$customers = count(Customer::all());
$data = [
'projects' => $projects,
'services' => $services,
'users' => $users,
'technologies' => $technologies,
'customers' => $customers
];
return new dataCollection($data);
Can someone help me please?
我不确定您的最终目标是什么,但问题似乎在于,正如错误所说,您将错误类型的数据发送到集合中。本例中的资源收集方法正在寻找一组对象,而您正在发送一个数组。
By the manual,它通过 User objects:
的集合寻找类似的东西
UserResource::collection(User::all()); // User collection, not the raw data array
如果您尝试通过某些 API 或 json 将数据发送回某人,我想您已经拥有了所需的东西 - 如果可以的话,也许可以跳过整个资源收集方法?所以试试这个:
$data = [
'projects' => Project::count(),
'services' => Service::count(),
'users' => User::count(),
'technologies' => Technology::count(),
'customers' => Customer::count()
];
return json_encode($data);
请注意,我稍微更改了代码以使其对您更有效率 - 您不需要先分配给变量 - 通过调用 ::all()
加 count()
,它将进行更繁重的数据库查询
资源上的 toArray()
方法实际上会将对象重新转换为上面的数组类型 - 因此我建议您通过跳过循环过程进行测试。
我正在尝试使用资源收集,但收到此错误“调用数组上的成员函数 toBase()”
The following code is in my resource :
class dataCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection
];
}
}
and here is code from the controller:
$projects = count(Project::all());
$services = count(Service::all());
$users = count(User::all());
$technologies = count(Technology::all());
$customers = count(Customer::all());
$data = [
'projects' => $projects,
'services' => $services,
'users' => $users,
'technologies' => $technologies,
'customers' => $customers
];
return new dataCollection($data);
Can someone help me please?
我不确定您的最终目标是什么,但问题似乎在于,正如错误所说,您将错误类型的数据发送到集合中。本例中的资源收集方法正在寻找一组对象,而您正在发送一个数组。
By the manual,它通过 User objects:
的集合寻找类似的东西UserResource::collection(User::all()); // User collection, not the raw data array
如果您尝试通过某些 API 或 json 将数据发送回某人,我想您已经拥有了所需的东西 - 如果可以的话,也许可以跳过整个资源收集方法?所以试试这个:
$data = [
'projects' => Project::count(),
'services' => Service::count(),
'users' => User::count(),
'technologies' => Technology::count(),
'customers' => Customer::count()
];
return json_encode($data);
请注意,我稍微更改了代码以使其对您更有效率 - 您不需要先分配给变量 - 通过调用 ::all()
加 count()
,它将进行更繁重的数据库查询
资源上的 toArray()
方法实际上会将对象重新转换为上面的数组类型 - 因此我建议您通过跳过循环过程进行测试。