2

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.

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

Just build the array with an if condition:

$matchThese = [
    'role' => 'user',
];
if(\Input::has('location')){
    $matchThese['place'] = \Input::get('location');
}
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();

1 Comment

thanks! It worked I also got the same answer from the Laravel slack, the only difference was that the user provided a shorthand if-statement.
0
   $query = DB::table('table_name');

   if($something == "something"){
      $query->where('something', 'something');
   }

   $some_variable= $query->where('published', 1)->get();    

You can use something like this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.