2

I know in Laravel 4 you can create a dynamic WHERE clause at runtime as from the following question:

Can you use query builder to build a query with a dynamic WHERE clause at runtime in laravel?

But can you do the same in laravel 3?

If not, is your only option instead to create raw SQL code as in the following:

$SQL = "SELECT * FROM " . $table;

$first = 1;
foreach($items as $key => $val)
{
   if($first) $SQL .= " WHERE ";
       else $SQL .= " AND ";
   $SQL .= $key . " LIKE " . $VAL;
   $first = 0;
}
Community
  • 1
  • 1
WildBill
  • 9,143
  • 15
  • 63
  • 87

3 Answers3

1

It works pretty much the exact same way. Just use $query = DB::table('tablename'); in place of the first line in the related post then use it as the rest of the example shows.

machuga
  • 426
  • 2
  • 2
  • That's not working. I get a `Method [all] is not defined on the Query class` – WildBill Apr 14 '14 at 14:08
  • Can you provide a small working example showing how this is accomplished in Laravel 3? – WildBill Apr 14 '14 at 14:30
  • @WildBill can you please show us the code that you are using that is requesting the "all" method? – Tim Groeneveld May 03 '14 at 23:52
  • As the other question suggests, I tried a ` $query = $tableModel->newQuery(); foreach($items as $key => $val) { $query->where($key, "LIKE", '%'.$val.'%'); } $query->all();` – WildBill May 06 '14 at 14:45
0

You can do this using something like this:

$query = DB::table($table);

if(isset($key1) && isset($val1)) {
    $query->where($key1, 'LIKE', $val1);
}

if(isset($key2) && isset($va2)) {
    $query->where($key2, '=', $val2);
}

$result = $query->get(); // returns all matching models

You can chain as many where clause as you need until you call the get() method. Also check this answer/L-4 to get another idea. Reading the Laravel - 3 manual would help you.

Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

You can use the query builder to perform queries such as this.

 $query = DB::table($table);

 // Get only the fields from the form that we care about...
 $form_fields = Input::get('email', 'username');

 // Build a dynamic query based on the form with WHERE's
 foreach ($form_fields as $name=>&$value) {
      $query->where($name, '=', $value);
 }

 // Finally get all of the results...
 $results = $query->get();

This does work fine in Laravel 3. Check out this [http://forumsarchive.laravel.io/viewtopic.php?id=1494] forum post for more information

Tim Groeneveld
  • 8,739
  • 3
  • 44
  • 60