I'm building a Laravel page on which I want to show a list of lessons. Which lessons should be on the page is filtered by three criterias (of which all should be true):
- The lesson is active, ie "where('active', true)". Simple enough.
- The lesson is part of a track that the user has chosen. Models are set up with belongsToMany() (it is a many-to-many relationship), so I can get these lessons by a simple $track->lessons.
- This is where it gets tricky. Some lessons should only be visible to users with certain titles (ie there is a many to many between titles and lessons). I can get the lessons with the correct title requirement using Auth::user()->title->lessons.
Question is how I get all this together. The best I've come up with this far is the following:
$title = Auth::user()->title;
$lessons = Lesson::where('active', true)
->whereIn('id', $track->lessons->pluck('id'))
->where(function ($query) use($title) {
$query->whereIn('id', $title->lessons->pluck('id'))->orWhere('limited_by_title', false);
})
->get();
...which is crap ugly, clearly suboptimal and (for some reason I reallly don't understand) also won't work (I don't get the lessons my title entitles me to in my list). Been struggling for quite some hours now, I get the feeling that I'm overcomplicating, first plucking id's and then using them in a whereIn() can't possibly be a good way of doing this.
So I can easily enough get a collection of lessons in the track, and I can get a collection of lessons belonging to the title, but how do I get all objects that exist in both those collections?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire