0

I have 3 models

Language: id,name.                Table: languages.|
Variant:id,name, language_id.    Table:variants.|
Symbol: id, name, variant_id.     Table :symbols.

Relations:
Language->hasMany->Variant.|
Variant->hasMany->Symbol.|
Language->hasManyThrough->(Symbol,Variant)

I wanted to find all symbols belonging to a language by language_id and pass a $symbols Query Builder Object paginated to my view from controller

I tried something like

$variants=Variant::with('symbol')->where('language_id',"=",$language_id)->get();
$symbols= collect(new Symbol);
foreach($variants as $variant){
$symbols->push($variant->symbol()->paginate(10));
}

return view(symbols.index,compact($symbols))

in the view I just echo the queried items in a foreach @foreach($symbols as $item) {{ $item->name; }}

This throws error in view as the passed object is a collection and not a Query returned result.

How do I convert this collection to Query builder result?

kishoreinme
  • 85
  • 3
  • 10

1 Answers1

1

Try something like this

$symbols = Symbol::whereHas('variant', function ($query) use ($language_id) {
    $query->where('language_id', $language_id);
})->paginate(10);

return view('index', ['symbols' => $symbols]);
Nikola Gavric
  • 3,507
  • 1
  • 8
  • 16
  • Basically, you've started the opposite way with your first try meaning that you should've started building your query from the object you wanted to fetch which in that case is Symbol, so a natural way of retrieving all symbols is by querying against them, not Variant. Function whereHas retrieves all models which have the relationship aka it's not null, if you pass a function as second parameter to whereHas, you are then querying the Variant table, so basically we are first retrieving all of the Symbols that have Variant which has a certain language_id. Hope this clarifies it – Nikola Gavric Feb 08 '18 at 18:47