Reputation: 1563
I am trying to fetch the the id and the name of the categories which is related to my services. A service has many categories and a categories belongs to a services. However when I try to get the id and the name as an array to return it gives me this error.
array_key_exists(): The first argument should be either a string or an integer.
Here is my method or function.
public function getCategories($idService)
{
$service = Service::findOrFail($idService);
return $service->categories->get(['id','name']);;
}
and here is the defined route.
Route::get('service/{service}/categories', 'ServiceController@getCategories');
I tried to look and browse for it but can't find any solution at all.
Upvotes: 3
Views: 3553
Reputation: 7489
Use pluck() method instead
return $service->categories->pluck('id','name');
Upvotes: 6
Reputation: 1262
The name of the parameter has to be equal to the wildcard and you need to use pluck() as mentioned in another comment, in your case:
public function getCategories($service)
{
$service = Service::findOrFail($service);
return $service->categories->pluck(['id','name']);
}
If service is a model you can also use eloquent:
public function getCategories(Service $service)
{
return $service->categories->pluck(['id','name']);
}
Upvotes: 1
Reputation: 9117
i guess it related to with
eager loading..need to use eager loading to fetch the relationship.. then use laravel collection if you want to filter more
public function getCategories($idService)
{
return Service::with(['categories' => function ($query) {
$query->select('id', 'name');
}])->findOrFail($idService);
}
Upvotes: 0