Ad

How Can I Build A Condition Based Query In Laravel Using Eloquent

- 1 answer

I was wondering how can I build a condition based query in Laravel using eloquent?

I've found how to do it with a raw query but that that's not what I want also the answer to this question isn't that dynamic at least not as dynamic as I want it to be.

What I try to achieve is to create a dynamic WHERE query based on certain conditions, for example if the field is filled or not.

If I use the following code,

        $matchThese = [
            'role' => 'user',
            'place' => \Input::get('location')
        ];

        $availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();

The query will fail if I don't send a location as POST value. I don't want it to fail I want it to skip to the next WHERE clause in the query. So basically if there's no place given don't search for it.

Ad

Answer

Build up the query and include the ->where() clause depending on whether or not you have the location in your input:

$query = User::where('role', 'user');

$query = \Input::has('location') ? $query->where('location', \Input::get('location')) : $query;

$availableUsers = $query->take($count)->orderByRaw('RAND()')->get();
Ad
source: stackoverflow.com
Ad