phplaravel-5eloquent

Add more conditions in Laravel 5.3 eloquent query by PHP IFs


In the case that I need to create a query which 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();

As Adam answered, is that simple:

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

 if($id_curso > 0)
     $aulas->where('id_curso', $id_curso);
            
 $aulas->where('condiotion_1');
    
 return $aulas->get();

$aulas is an object, and I was thinking like it was the query string, so thanks Adam.


Solution

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