Object of class Illuminate\Database\Eloquent\Builder could not be converted to string in laravel 5.1
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.
- In your example, the
$term
variable is never used. I am assuming that it should be an array of category ids. - I'm also assuming that
$term
is what you want to pass into thewhere
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();
You don't need to use both take()
and get()
. Just just one or the other.