Answer the question
In order to leave comments, you need to log in
Laravel. How to search in many to many relationship?
There is a list of books. Each book is associated with an author and a store. Each book can have multiple authors or stores, so many to many relationships are used here. There is a form with checkboxes: with authors, stores and books. When you click on these checkboxes, the corresponding books should be displayed. How to write a query so that a filter occurs simultaneously for both the author and the store. This can be done through whereHas, but how to do several whereHas at the same time and take into account that, for example, the author or store may not be selected.
Answer the question
In order to leave comments, you need to log in
$book = Book::select('id', 'name');
if ($author) {
$book = $book->whereHas(...);
}
if ($shop) {
$book = $book->whereHas(...);
}
$results = $book->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question