0

So Basically i have the model foo:

protected $with = ['bars'];

public function bars()
{
   return $this->morphMany(bar::class, 'barable');
}

And the model bar:

public function barable() 
{
   return $this->morphTo();
}

Now my question is, if i want to load foo via bar:

Bar::find(1)->with(['barable.something.this'])->get();

I get the foo table alongside with the corresponding bar.

Now because the bars attribute of foo has many entries (including the original bar which i request the foo through) i want to exclude the barable.bars, but since its included in the with attribute, it's always loaded.

How can i exclude barable.bars from my query?

edit: I'm using laravel 5.6 if that matters

ScarVite
  • 327
  • 1
  • 5
  • 19
  • remove `protected $with = ['bars'];` – V-K Jan 28 '21 at 11:14
  • problem being, this is the only case in which i don't need bars, in every other query i need bars – ScarVite Jan 28 '21 at 11:18
  • ok, in this case, you can use `makeHidden` function – V-K Jan 28 '21 at 11:19
  • Tried it like this: `Bar::find(1)->makeHidden(['barable.bars'])->with(['barable.something.this'])->get();` But im getting `Method Illuminate\Database\Query\Builder::makeHidden does not exist.` as an error – ScarVite Jan 28 '21 at 11:27

1 Answers1

2

Try using $books = Book::without('author')->get(); like written in documentation.

So in your case it would be

Bar::find(1)->with(['barable' => function ($query){ $query->without('bars'); $query->with(['something.this']) }])->get();

Miqayel Srapionyan
  • 587
  • 2
  • 5
  • 15
  • How would i implement this if i want to use Books::find or Books::orderBy? – ScarVite Jan 28 '21 at 11:41
  • Can you try like this? `Books::find(1)->without('author')->get();` or `Books::without('author')->orderBy('id')->get();` – Miqayel Srapionyan Jan 28 '21 at 11:48
  • if i try it like `Books::find(1)->makeHidden(['barable.bars'])->with(['barable.something.this'])->get();` i get `Method Illuminate\Database\Query\Builder::makeHidden does not exist` and using `Books::makeHidden(['streamable.streams'])->orderBy('id')->with(['barable.something.this'])->get();` I get: `Non-static method Illuminate\Database\Eloquent\Model::makeHidden() should not be called statically` – ScarVite Jan 28 '21 at 11:51
  • have you tried method `without` not `makeHidden` ? – Miqayel Srapionyan Jan 28 '21 at 11:54
  • if you mean `Books::find(1)->without(['barable.bars'])->with(['barable.something.this'])->get()` it includes barable.bars – ScarVite Jan 28 '21 at 11:56
  • i don't know if this is important for that matter, but i don't use the latest version, i am using 5.6 (edited question to include it) – ScarVite Jan 28 '21 at 12:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227959/discussion-between-scarvite-and-miqayel-srapionyan). – ScarVite Jan 28 '21 at 12:21