Laravel Restful API - How to create custom query based on multiples params

1.2k Views Asked by At

I am new to Laravel. I have created a Restful API with this route : (with Laravel 5)

Route::get('api/clubs', 'Api\ClubsController@getClubs');

Calling /public/api/clubs will retrieve all clubs $clubs = Club::all();

With the same route I am trying to filter clubs based on many params :

        $filter_lat      = Request::get( 'fi_lat' );
        $filter_long     = Request::get( 'fi_long' );
        $filter_distance = Request::get( 'fi_distance' );
        $filter_key_word = Request::get( 'fi_key_word' );
        $filter_date     = Request::get( 'fi_date' );
        $filter_city_id  = Request::get( 'fi_city_id' );
        $filter_order_by = Request::get( 'fi_order_by' );
        $filter_offset   = Request::get( 'fi_offset' );
        $filter_limit    = Request::get( 'fi_limit' );

I want to filter my clubs based on those params, but I don't know what is the best way to build the query using Eloquent. I want to be able to run the query even if I have only 1 param. example1 : I want to filter my clubs by city and my query will looks like :

$clubs = Club::where( 'city_id', $filter_city_id )->get();

If I have more params my query will looks like :

$clubs = Club::where( condition 1 )

->where( condition 2 )

->where( condition 3 ) etc ..

->get();

How to build my query this way and put together all conditions ?

if( !empty ( $my_param ) ){
$query += where ( condition .. )
}

then run $query ..

What I don't want to do, is doing 10 "if() tests" and build 10 queries depending on params because this will be really a big code hacking and duplicated query ..

I am open to any suggestions, I want to have an object of clubs as result. Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

It's quite simple, just check that each condition was passed and if it did, add a where clause.

$query = Club::newQuery();

    if($my_param) {
        $query->where('my_param', $my_param);
    }

    if($my_param2) {
        $query->where('my_param2', $my_param2);
    }

    $clubs = $query->get();

You should check that the variable is set simply because it's good practice when dealing with user submitted data. If there are some parameters which you need to validate further, be sure to use the validation class.

0
On

You can use array inside where() . like this:

User::where(['id' => $id, 'name' => $name, 'etc' => $etc])->get();

:)...