Moisés Moisés - 1 month ago 17
PHP Question

Add more conditions in Laravel 5.3 eloquent query by PHP IFs

In the case that I need to create a query wich will change depending on php parameters, how can I mount eloquent's query piece by piece?

Like in this case:

if($id_curso > 0)
$aulas = Aula
::select( 'fields' )
->where('id_curso', 3)
->where('condition_1');
else
$aulas = Aula
::select( 'fields' )
->where('condition_1');

return $aulas->get();


That does the trick, but when I change the SELECT or WHERE I'll have to change in both cases, is there a way to do something like this:

$aulas = Aula
::select( 'fields' );

if($id_curso > 0)
$aulas.= Aula::where('id_curso', 3);

$aulas.= Aula::where('condition_1');

return $aulas->get();

Answer

Off the top of my head from memory you can do something like:

$aulas = Aula::select( 'fields' );

if($id_curso > 0) {
    $aulas->where('id_curso', 3);
} else {
    $aulas->where('condition_1');
}

$aulas->get();

If that dosent work you can do it this way (not sure if it will run from the model or has to be from the DB::table(), you will need to "use DB;" too ):

$query = DB::select('table');
if($id_curso > 0) {
    $query->where('id_curso', 3);
} else {
    $query->where('condition_1');
}

$query->get();
Comments