laravel when condition code example

Example 1: 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 2: laravel when condition

$invisiblePosts = $request->query('invisible');

Article::query()
            ->when($invisiblePosts , function ($query){
                return $query->where('invisible' , true);
            },function ($query){
                return $query->where('invisible' , false);
            })
            ->get();

Example 3: when in larevel

$role = $request->input('role');

$users = DB::table('users')
                ->when($role, function ($query, $role) {
                    return $query->where('role_id', $role);
                })
                ->get();

Example 4: laravel if else condition in query

$query = SocialMediaFeed::where('location_id', $location_id);
if(!$filters) {
    $query = $query->where('self', '<>', true);
} else {
    $query = $query->orWhere('self', true);
}

Tags:

Misc Example