Object of class IlluminateDatabaseEloquentBuilder could not be converted to string in laravel 5.1

Tags: ,



I have been trying to debug a problem for the past two days, my code, as follows, is first attempting to retrieve the category by it’s id:

$term = category::get(['id']);

Then using this retrieved term for querying models with a foreign key on that category:

$categories = HelpCenter::whereHas('category', function($category) use ($term)
{
    $category->where('category_id','=',$category);
})
  ->take(5)->get();

Unfortunately my code throws the error Object of class IlluminateDatabaseEloquentBuilder could not be converted to string

Answer

This line of code does not make sense:

$category->where('category_id','=',$category);

$category is an Eloquent Builder instance so what you are effectively doing is this:

EloquentBuilder->where('category_id', '=', EloquentBuilder);

I’m assuming the second $category variable was meant to be $term like this:

$category->where('category_id','=',$term);

But that will still cause some issues, which I’ll explain in a bit. First though, I think you should rename the variable so it makes a bit more intuitive sense. Instead of $category, name it $query so things don’t get mixed up.

$categories = HelpCenter::whereHas('category', function($query) use ($term)
{
    $query->where('category_id', '=', $term);
})
->take(5)->get();

Next, we need to tackle a few more things.

  1. In your example, the $term variable is never used. I am assuming that it should be an array of category ids.
  2. I’m also assuming that $term is what you want to pass into the where method.

To tackle #1, you are currently getting a collection of category instances. You’re actually getting every single category in your database. I’m not sure if that’s your intention, but either way, you probably still want an array of category ids. As @smartrahat suggested, use the pluck method.

$term = category::get(['id'])->pluck('id');

To tackle #2, you want to find all categories that match the ids you are passing. You can use the whereIn method for that.

$query->whereIn('category_id', $term);

All together, it should look something like this:

$term=category::get(['id'])->pluck('id');

$categories = HelpCenter::whereHas('category', function($query) use ($term)
{
    $query->whereIn('category_id', $term);
})
->take(5)->get();


Source: stackoverflow