3

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.

3 Answers 3

6

Use pluck() method instead

return $service->categories->pluck('id','name');
Sign up to request clarification or add additional context in comments.

Comments

1

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']);
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.