Amitav Roy Amitav Roy - 3 months ago 13
PHP Question

How can I build a condition based query in laravel

I can do this in Code Igniter

$this->db->select();
$this->from->('node');
if ($published == true)
{
$this->db->where('published', 'true');
}
if (isset($year))
{
$this->db->where('year >', $year);
}
$this->db->get();


I am not able to do this in Laravel. Guys can you please help.

Answer

In Fluent you can do:

$query = DB::table('node');

if ($published == true)
    $query->where('published', '=', 1);

if (isset($year))
    $query->where('year', '>', $year);

$result = $query->get();