Monday, 24 October 2016

Apply where condition if input exists in Laravel Eloquent ORM

If you want to apply multiple where condition based on whether particular inputs are present in laravel Eloquent ORM, we can use the array applied within the where.

Consider we are having the Movie table with its fields id, name, genre, year. we want to gets all movies list with or without genre and year.

public function getMovies($input) {
    $condition = array();
    if(!empty($input['genre'])){
        array_push($condition, ['genre', $input['genre']]);
    }
    if(!empty($input['year'])){
        array_push($condition, ['year', $input['year']]);
    }
    
    $result = Movie::where($condition)->get();
    return $result;
}

No comments:

Post a Comment