In this tutorial you will learn about the Laravel Eloquent selectRaw Query Tutorial and its application with practical example.
In this Laravel Eloquent selectRaw Query Tutorial I will show you how to use selectRaw method to create select raw queries in laravel application. In this tutorial you will learn to create raw queries using eloquent selectRaw method in laravel application. In this article I will share various example to use selectRaw method to create select raw queries in laravel. We will also create select raw query with multiple conditions.
Laravel Eloquent selectRaw Query Tutorial
In this step by step tutorial I will demonstrate various examples on how to use selectRaw() eloquent query in laravel:
- Laravel selectRaw Query using Model
- selectRaw Query using Query Builder
- Laravel selectRaw with joined table data
Example 1: Laravel selectRaw Query using Model
In this example we will be using selectRaw method using model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $users = User::select("*") ->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:
1 |
select *, amount + ? as amount_with_bonus from `users` |
Example 2: selectRaw Query using Query Builder
In this example we will be using selectRaw method with query builder:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use DB; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $users = DB::table('users')->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:
1 |
select *, amount + ? as amount_with_bonus from `users` |
Example 3: Laravel selectRaw with joined table data
In this example we will be using selectRaw with joins:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use DB; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $users = DB::table('users') ->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); } } |