Laravel Eloquent selectRaw Query Tutorial


Laravel selectRaw() query example; In this tutorial, you will learn in detail how to write select raw and select DB raw query in laravel. And as well as learn, how to use selectRaw with joined table data.

You can use the laravel selectRaw eloquent method to building query in laravel apps. And also use laravel select raw with multiple conditions in eloquent queries.

So, let’s see following examples that will help you how to use selectRaw() eloquent query in laravel:

  1. Example 1: Laravel selectRaw Query using Model
  2. Example 2: selectRaw Query using Query Builder
  3. Example 3: Laravel selectRaw with joined table data

Example 1: Laravel selectRaw Query using Model

selectRaw('amount + ? as amount_with_bonus', [500])
                        ->get();
        dd($users);
    }
}

When you dump the above given selectRaw query you will get the following SQL query:

select *, amount + ? as amount_with_bonus from `users`

Example 2: selectRaw Query using Query Builder

select("*")
                        ->select('*', DB::raw('amount + 500 as amount_with_bonus'))
                        ->get();
  
        dd($users);
    }
}

When you dump the above given selectRaw query you will get the following SQL query:

select *, amount + ? as amount_with_bonus from `users`

Example 3: Laravel selectRaw with joined table data

where('active','true')
                  ->join('user_types', 'users.user_type_id', '=', 'user_types.id')
                  ->groupBy('user_type_id','user_types.name')
                  ->selectRaw('sum(total) as sum, user_types.name as name')
                  ->pluck('sum','name');
  
        dd($users);
    }
}

Recommended Laravel Tutorials



Leave a Reply

Your email address will not be published. Required fields are marked *