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.

Community
  • 1
  • 1
0x1ad2
  • 8,014
  • 9
  • 35
  • 48

3 Answers3

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();
Steve
  • 20,703
  • 5
  • 41
  • 67
  • 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. – 0x1ad2 Jan 12 '16 at 13:02
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();
Sven
  • 444
  • 3
  • 7
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.

MasterSith
  • 175
  • 6