6
votes

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 Illuminate\Database\Eloquent\Builder could not be converted to string

3
what are you doing with that single item array in the get function?madalinivascu
This is only part of your code, you are trying to dump/debug the Query Builder (probably using echo); that is what the message is saying. Please provide the complete code that is throwing the backtrace.Luceos
To get id of category from databasePawan Dongol
Change $term=category::get(['id']); to $term=category::all()->pluck('id') to have all id in array.smartrahat

3 Answers

9
votes

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();
2
votes

You don't need to use both take() and get(). Just just one or the other.

0
votes
$product = $data->with('productimages')->with('categories')->where('id', $id)->first();