1

suppose i have a function like bellow (in Laravel 4.2):

public static function getResult($class_id,$section_id,$session,$term,$setTerm = ture)
{
     $result = self::with('Student','Student.getClass','Student.getSection')
        ->where('class_id',$class_id)
        ->where('section_id',$section_id)
        ->where('exam_year',$session)
        ->where('term',$term)
        ->orderBy('class_roll','ASC')->get();

    return $result;

}

so if $setTerm is set to false then (->where('term',$term)) should not be executed.

How to do that conditional things in Laravel during query building ?

Thanks

2 Answers 2

1

Please try it, this should work:

public static function getResult($class_id,$section_id,$session,$term,$setTerm = ture)
{
     $result = self::with('Student','Student.getClass','Student.getSection')
        ->where('class_id',$class_id)
        ->where('section_id',$section_id)
        ->where('exam_year',$session);

     if($setTerm){ 
        $result->where('term',$term);
     }

     $result->orderBy('class_roll','ASC')->get();

     return $result;

}
Sign up to request clarification or add additional context in comments.

Comments

1

You can change the function to be this:

public static function getResult($class_id,$section_id,$session,$term,$setTerm = true)
{
     $query = self::with('Student','Student.getClass','Student.getSection')
        ->where('class_id',$class_id)
        ->where('section_id',$section_id)
        ->where('exam_year',$session);

    if ($setTerm) {
        $query->where('term',$term);
    }

    return $query->orderBy('class_roll','ASC')->get();    
}

1 Comment

One little flaw, you have to assign the return value of get() to $query or return it directly. Otherwise getResult() will return a query builder instance and not the actual result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.