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

codingislife's avatar

Filter MongoDB results dynamically with where() and URL query string

Hello forum members,

right now I'm trying to implement a restful API where users can filter a resource dynamically with the key value pairs in the url query string. All data are stored in MongoDB and are queried using laravel-mongodb.

Let's suppose I've a resource called Persons where I would like to optionally filter by name and age. The url would look like this:

www.example.com/api/v1/persons?name=John&age=33

But how do I apply these filters using laravel-mongodb's where()-function? My model looks as follows:

<?php

namespace App\Http\Controllers;

use App\Persons;
use Illuminate\Http\Request;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use DB;

class PersonsController extends Controller {

    public function getPerson(Request $request) {
        $persons = Person::all()
             ->where('name', $request->input('name'));
             ->where('age', $request->input('age'));

        return response()->json($persons);
    }
}

Once the where()-function calls are part of the query no results are shown. Has anyone of you an elegant solution?

0 likes
0 replies

Please or to participate in this conversation.