Reputation: 3
I am trying to use Laravel's Eloquent ORM with conditional statements for example, in Codeigniter I can use the following syntax to filter my database results;
<?php
$this->db->select('*')->from('demos');
if (isset($data) && is_numeric($data) )
{
$this->db->where('type_id', $data);
}
if (isset($name) && is_string($name) )
{
$this->db->where('name', $name);
}
return $this->db->get(); ?>
I have tried the same implementation which doesn't seem to work; how do I replicate the above using Eloquent?
Thanks for your assistance
Upvotes: 0
Views: 4420
Reputation: 116
In newer versions of Laravel (5.2.27 and up) you can actually do something similar to:
$results = DB::table('orders')
->when($request->customer_id, function($query) use ($request){
return $query->where('customer_id', $request->customer_id);
})
->get();
Hope that will help for newcomers
Upvotes: 0
Reputation: 3374
Since you did not provide any information about Models, you can use Query Builder instead of Eloquent.
$data = Input::get('data', null);
$types = DB::table('demos')->where('type_id', '=', $data)->get();
and for the second part
$name = Input::get('name', null);
$names = DB::table('demos')->where('name', '=', $name)->get();
you can also short it to just
$data = Input::get('data');
$types = DB::table('demos')->whereData($data)->get();
$name = Input::get('name');
$names = DB::table('demos')->whereName($name)->get();
EDIT
Following the comment, I figured out that the query should be connected.
$data = Input::get('data');
$name = Input::get('name');
$result = DB::table('demos')
->where('type_id', $data)
->whereName($name)
->get();
Upvotes: 0
Reputation: 1239
Try the following, if you have your models set up:
$demos = Demo::query();
if (isset($data) && is_numeric($data) )
{
$demos->where('type_id', $data);
}
if (isset($name) && is_string($name) )
{
$demos->where('name', $name);
}
return $demos->get();
Thanks for the suggestion, @JofryHS. Code updated accordingly.
Upvotes: 7