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

lat4732's avatar
Level 12

Problem with query builder

Hello everyone!

I have the following query:

        $reviews = Reviews::query();

        if(!empty($request->stars)) {
            foreach($request->stars as $star) {
                $reviews->orWhere('review_stars', '=', $star);
            }
        }

        $reviews->orderBy('created_at', 'desc')->paginate(6);

compacted and sent to the blade template file with compact(). But I'm receiving no results from the database. Any ideas why? Also when I try to add {{ $reviews->links() }} I'm getting the following error:

Call to undefined method Illuminate\Database\Eloquent\Builder::links()

Any ideas? I've done this in other pages in my project but never faced these problems.

0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You need to get the returned result. This probably makes more sense.

$query = Reviews::query();

        if(!empty($request->stars)) {
            foreach($request->stars as $star) {
                $query->orWhere('review_stars', '=', $star);
            }
        }

        $reviews = $query->orderBy('created_at', 'desc')->paginate(6);
lat4732's avatar
Level 12

@Sinnbeck Not sure why I can't just pass the $reviews variable without assigning the returned result to another variable but yeah, it worked!

Sinnbeck's avatar

@crypt.001111101 Because of how php works..

$reviews = Reviews::query(); // here we make an instance of the Builder class

        if(!empty($request->stars)) {
            foreach($request->stars as $star) {
                $reviews->orWhere('review_stars', '=', $star); // here we change stuff inside the builder class. Same as if you have a User class and you did $user->name = 'foobar';
            }
        }

        $reviews->orderBy('created_at', 'desc') //again we change stuff inside the the Builder class
->paginate(6); //and here we call a method that prepares the Builder class for pagination internally... and then returns a new result.. But you never get that result (you get that by assigning it to something)
1 like

Please or to participate in this conversation.