Laravel conditions in Controller where clause

Alejandro Beltran picture Alejandro Beltran · Jun 30, 2014 · Viewed 9.4k times · Source

I'm trying to build a query based on URL parameters. When the Controller is loaded I need to check which parameters have been provided and build a query from them. It's working with static values, but isn't working with conditional statements. Is my laravel syntax correct?

class OrdenesController extends BaseController {

public function showOrdenes($action)
{
  $my_id = Auth::user()->id;
  $my_cod = Auth::user()->codprov;

  switch ($action) 
  {
    case 'list':
      $rows = DB::table('ordens')->count();
      if(Input::get("jtSorting"))
      {
       $search = explode(" ", Input::get("jtSorting"));            
       $numorden= Input::get("nro_orden");
       $filtros =explode(" ", $filtros);

       $data = DB::table("ordens")
        ->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
        ->where('cod_prov', '=', $my_cod)

        ->where('nro_orden', '=', $numorden)///work

        ---------- ////no work
        if (Input::has('nro_orden')) {
           ->where('nro_orden', '=', $numorden)
        }
        ---------- /// no work

        ->groupBy('nro_orden')
        ->skip(Input::get("jtStartIndex"))
        ->take(Input::get("jtPageSize"))
        ->orderBy($search[0], $search[1])
        ->get();
      }
      return Response::json(
        array(
          "Result"      =>    "OK",
          "TotalRecordCount"  =>    $rows,
          "Records"     =>    $data
        )
      );
      break;

   };  
  }    
}

Answer

Unnawut picture Unnawut · Jun 30, 2014

You are missing the variables, no? You haven't told PHP what variable/object to do the where() to in your condition. The magic of Laravel's Eloquent (and a lot of other libraries) is that when you call its methods, it returns itself (the object) back so you can make another method call to it right away.

So when you do this:

$data = DB::table("ordens")
    ->select(...)
    ->where(...);

is the same as:

$data = DB::table("ordens");
$data = $data->select(...);
$data = $data->where(...);

But you are trying to do ->where(...) right away after if condition. You need to tell PHP which object/variable you are trying to call the method from. Like this:

$num = Input::get("nro_orden");

$data = DB::table("ordens")
    ->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
    ->where('cod_prov', '=', $my_cod);

if (Input::has('nro_orden')) {
    $data = $data->where('nro_orden', '=', $num);
}

$data = $data->groupBy('nro_orden')
    ->skip(Input::get("jtStartIndex"))
    ->take(Input::get("jtPageSize"))
    ->orderBy($search[0], $search[1])
    ->get();