laravel eloquent with condition code example
Example 1: laravel adding condition to relation
class Game extends Eloquent {
public function videos() {
return $this->hasMany('Video');
}
public function available_videos() {
return $this->videos()->where('available','=', 1)->get();
}
}
Example 2: laravel where condition with if
$query = DB::table('user_ads')
->join('ads', 'users_ads.ad_id', '=', 'ads.id')
->orderBy($column, $method);
if ($input['search']) {
$query->where('short_description', $input['search']);
}
if ($input['category']) {
$query->where('category', $input['category']);
}
$query->join('users', 'users_ads.user_id', '=', 'users.id')
->select('ads.id', 'ads.img1', 'ads.short_description', 'ads.category', 'ads.product', 'ads.price', 'users.city')
$result= $query->get();
return $result;
Example 3: condition for both of one should be true laravel eloquent
WHERE age < 6 OR (age > 8 AND name IN ('Jane', 'Jerry'))
return \App\Dogs::select('name', 'age')
->where('age','<', 6)
->orWhere(function($q){
$q->where('age','>', 8);
$q->whereIn('name', ['Jane', 'Jerry']);
})
->get();