Tomkarho
Tomkarho

Reputation: 1817

Laravel 4: optional wherein clause

Basically I have a routing system in Laravel that passes on an optional high level tag name which is used to retrieve a list of tags from a database collection (I am using MongoDB) and use that tag list in turn to retrieve data from another collection.

My Controller:

public function index($tag){
   $tags = array();

if ($tag){
//get an array of tags from db
}

$data = DB::collection('notices')
->whereIn("tags", $tags //<-- an array of tags)
->GET(...);
}

Now when I do give a tag and there is an array to pass on to the whereIn clause then the data is retrieved as expected. However if parameter is not give then the query returns an error as there is nothing to query with.

As such I need to know whether it is possible in Laravel to either make the ->whereIn optional somehow or give an array to it so the query acts as if there is no where clause

Upvotes: 1

Views: 2096

Answers (2)

Alexander Ivanov
Alexander Ivanov

Reputation: 140

In Laravel 5+ you can use "Conditional Clauses": https://laravel.com/docs/5.3/queries#conditional-clauses

$role = $request->input('role');

$users = DB::table('users')
                ->when($role, function ($query) use ($role) {
                    return $query->where('role_id', $role);
                })
                ->get();

Upvotes: 0

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87779

That's what you're looking for:

public function index($tag){
    $tags = array();

    $data = DB::collection('notices');

    if ($tag){
        //get an array of tags from db
        $data->whereIn("tags", $tags //<-- an array of tags)
    }

    $data->get(...);
}

Upvotes: 2

Related Questions