Reputation: 51
In codeigniter I used to write query on separate line using ';' separeted instead of '->' sign, example:
$color = 'red';
$this->db->select('id, name');
if($color){
$this->db->where('color', $color);
}
$query = $this->db->get('product');
Same thing I want in laravel. color where clause should be apply when I select color.
$query = DB::table('product')
if($color){
->whereColor($color)
}
->get();
But its showing error "syntax error, unexpected 'if'" How do I write such query in laravel?
Upvotes: 1
Views: 1130
Reputation: 5588
Please, add where clause like $query->where('color', '$color');
$color = 'red';
$query = DB::table('product');
if($color){
$query->where('color', '$color');
}
$rows = $query->get();
============ Another way is:
$rows = Product::where_color('$color')->get();
Upvotes: 0
Reputation: 422
u need chain, u cant use "->" operator without object: try chain, using $query varabile, like this:
$query = DB::table('product'); // create instance
if($color){
$query->whereColor($color); // chain here
}
$query = $query->get(); // get result
Upvotes: 0
Reputation: 26477
Method chaining returns the query object. So you can use your $query
variable.
$query = DB::table('product');
if($color){
$query->whereColor($color);
}
$query->get();
Don't forget to put a ;
on the end of each line still.
Upvotes: 1