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

spoon's avatar

Eloquent where

Hi!

I want to get the all books that has been read by a user, but I kinda stuck here.

My usersxbook_progress table has three columns and they are foreign keys. user_id, progress_id and thing_id. progress_id = 1 means that book is completed, but how do I list only completed books by a user?

User Model

    public function usersBooks1() {
        return $this->belongsToMany('App\Models\Thing', 'usersxthing_progress','user_id','thing_id');
    }

Controller

        $allbooks = User::find($user_id)->usersBooks1;

View

@foreach($allbooks as $books)
    {{$books->name}}
@endforeach
0 likes
4 replies
bobbybouwmann's avatar

You can use where statements on the relations

$user = User::with('userBooks1' => function($query) {
    $query->where('progress_id', '=', 1)
)->find($user_id);

$allBooks = $user->usersBooks1;
spoon's avatar

@bobbybouwmann It doesn't work, I think you forgot to put the curly braces, so I tweaked it a little bit. I get Undefined variable: allbooks error.

        $user = User::with(array('userBooks1' => function($query)
        {
            $query->where('progress_id', '=', 1)->find($user_id);

            $allBooks = $user->usersBooks1;
        }));
bobbybouwmann's avatar
Level 88

The query is in the callback so your results should be outside of it

$user = User::with(array('userBooks1' => function($query) {
    $query->where('progress_id', '=', 1)
})->find($user_id);

$allBooks = $user->usersBooks1;

As you can see the callback will only apply on the userBooks1 relation. You can then continue your query. You clearly have not enough knowledge of Laravel and Eloquent. Start with reading the documentation before you continue: http://laravel.com/docs/5.1/eloquent-relationships

spoon's avatar

@bobbybouwmann

I never close Laravel docs tab, but you are right.

I added a semicolon and this version works.

        $findBooks = User::with(array('usersBooks1' => function($query) {
            $query->where('progress_id', '=', 1);
        }))->find($user_id);
        $allBooks = $findBooks->usersBooks1;

Please or to participate in this conversation.