Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Chaining based on condition

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');
like image 817
eaponz Avatar asked Aug 19 '14 08:08

eaponz


1 Answers

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);
like image 187
JofryHS Avatar answered Oct 09 '22 05:10

JofryHS