9

How can you do method chaining based on condition in laravel 4 ? Say if one value is not false then the method inside will be chained to the method called before the if statement.

Is it possible in laravel?

$data = User::where('username', $somevariable );

if(isset( $somevar_again ))
{
  $data->where('age', 21);
}
$data->orderBy('reg_date', 'DESC')->get();
return $data->first();

// tried code above and its giving me wrong result in codeigniter I can do this

$this->db->select('e.*, v.name_en as v_name_en')
    ->from($this->table_name . ' e, ' . $this->ptc_venues . ' v');
  $this->db->where('e.venue_id_en = v.id'); 

  if(isset($search)){
   $this->db->where('(v.name_en LIKE "%'.$search.'%")');
  }

  $this->db->limit($limit, $start);
  $this->db->order_by('e.added_date_en', 'DESC');
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
eaponz
  • 574
  • 1
  • 16
  • 32
  • You are calling `get()` which returns all the results and then call `first()` which basically ads a `LIMIT 1` to the generated SQL query and runs it. Why are you calling `->get()` at all? – Sergiu Paraschiv Aug 19 '14 at 09:38
  • Almost relevant page: https://stackoverflow.com/q/12351737/2943403 – mickmackusa Nov 28 '20 at 21:13

2 Answers2

21

I believe your problem happened because you didn't store back the resulting query after each query builder method call.

$query = User::query();

// Checking for username if exists
if (!empty($username)) {
    $query = $query->where('username', $username);
}

// Check for age if exists
if (isset($age)) {
    $query = $query->where('age', $age);
}

// Ordering
$query = $query->orderBy('reg_date', 'DESC');

// Get the first result
// After this call, it is now an Eloquent model
$user = $query->first();

var_dump($user);
JofryHS
  • 5,804
  • 2
  • 32
  • 39
0

From Laravel 5.2 and onward, you can utilise Conditional Clauses/Statements:

Sometimes you may want statements to apply to a query only when something else is true. For instance you may only want to apply a where statement if a given input value is present on the incoming request. You may accomplish this using the when method

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.

You can use the code as follows:

$data = User::where('username', $somevariable)
              ->when( isset($somevar_again), function ($query) {
                      return $query->where('age', 21);
                   })
              ->orderBy('reg_date', 'DESC')
              ->get();
return $data->first();

Also, note that Laravel 5.3+, it has further been extended as documented below:

You may pass another Closure as the third parameter to the when method. This Closure will execute if the first parameter evaluates as false

Community
  • 1
  • 1
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57