Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ppigerr's avatar

Filter model by value of related object (one to many)

Hello, my first time here :D I have models: Book, BookRoute and Users. Users can register the route of the book then row with id, user_id, book_id and date is created. I need to show only books which were registered by the current user as last (BookRoute with this user_id is the last for this book). I want to do this in livewire, so the best option I found is macro for Builder (then I can paginate etc.). How can I write this macro? Can I use it in this way:

‘books’ => Book::when($only_current_user_books, fun($query){ return …. }->(second when condition)->paginate(10); ???

0 likes
3 replies
tykus's avatar

Use whereHas Builder method.

ppigerr's avatar

@tykus How can I add condition if last route of book is related with current user? I'm thinking about group then last(). I have function for Book which return last BookRoute for Book.

ppigerr's avatar

I have: User > one to many > BookRoute > many to one > Book.

I need to get Books which in last BookRoute have specified User.

I did this:

@foreach ($books as $book)
    @if ($my_books_filter && $book->last_book_route()->user_id != auth()->user()->id)
        @continue
    @endif
{{--code to show book--}}
@endforeach

But this not working with pagination, pages aren't same size.

EDIT: I want to avoid create current_user_id column in Book

Please or to participate in this conversation.