I am trying to search for all Rents that have a RentItem with a book title LIKE the given $input.
The problem is when the input does not match,I still get a collection returned. The only difference is that the book relation is null instead of a collection.
Result of query that should return false: https://pastebin.com/pd7UqhCi
Result of query that is true: https://pastebin.com/shndvdMh
When book equals null, I do not want the Rent model to be returned.
My query
$rents = Rent::with(['rentItems.book' => function ($query) use ($input) {
$query->where('books.title', 'LIKE', "%$input%");
}])->get();
Rent model Relation
public function rentItems()
{
return $this->hasMany(RentItem::class);
}
RentItems model Relations
public function book()
{
return $this->belongsTo(Book::class);
}
public function rent()
{
return $this->belongsTo(Rent::class);
}
Research i have done:
You need to use the whereHas()
method. Do something like this:
$rents = Rent::whereHas('rentItems.book', function ($query) use ($input) {
$query->where('books.title', 'LIKE', "%$input%");
})->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With