How can I build a condition based query in Laravel?

As of Laravel 5.2.27, you can avoid breaking the chain by writing your conditions as so:

$query = DB::table('node')
    ->when($published, function ($q) use ($published) {
        return $q->where('published', 1);
    })
    ->when($year, function($q) use ($year) {
        return $q->where('year', '>', $year);
    })
    ->get();

To use Eloquent,just swap $query = DB::table('node') with Node:: but realize if both conditions fail, you'll get everything in the table back unless you check for some other condition before querying the db/model or from within the query itself.

Note the that $published and $year must be in local scope to be used by the closure.

You can make it more concise and readable by creating a macro. See: Conditionally adding instructions to Laravel's query builder


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();

Tags:

Php

Laravel