lundi 6 août 2018

How to `if` for two same values in eloquent `when`

How can I convert this:

if(isset($from) && isset($to))
{
    $query->where('column1', $from)->where('column2', $to);
}
elseif(isset($from))
{
    $query->where('column1', $from);
}
elseif(isset($to))
{
    $query->where('column1', $to);
}

to something like this with when in Laravel:

...
->when(isset($from) && isset($to), function($query) use ($from, $to)
{
    $query->where('column1', $from)->where('column2', $to);
})
->elseWhen(isset($from), function($query) use ($from)
{
    $query->where('column1', $from)->where('column2', $from);
})
->elseWhen(isset($to), function($query) use ($to)
{
    $query->where('column2', $to);
});

Thanks

Aucun commentaire:

Enregistrer un commentaire