In this post we will explain of Laravel eloquent selectRaw() example. You will learn Laravel selectRaw query example. Sometimes you need to perform more complex query such as raw SQL queries for aggregate function. This is where the selectRaw() method become valuable. We will explore how to use selectRaw() in with practical example.
1. Understand Laravel eloquent selectRaw()
selectRaw() allow you to write raw SQL expression within your eloquent query. When you need to perform operation not directly supported by eloquent’s syntax. You can easily implement select raw query in Laravel.
Syntax:
Model::selectRaw('raw_sql_expression')->get();
2. Example of Using selectRaw()
You can use selectRaw() to combine multiple column into one.
Example 1:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index()
{
$users = User::select("*")->selectRaw('price + ? as price_with_bonus', [500])->get();
dd($users);
}
}
Output:
"id" => 1
"name" => "Jasminkumar "
"email" => "boradjasminkumar74@gmail.com"
"email_verified_at" => "2024-12-13 12:07:52"
"password" => "$2y$10$R9EL25MVwMf8cksTAKuoOOdf4hiVLLqY.xcXsCDlD8FFyNvnWs9fa"
"price" => 1000
"remember_token" => null
"created_at" => "2024-12-13 12:07:51"
"updated_at" => "2024-12-13 12:07:52"
"price_with_bonus" => 1500
Example 2: Laravel Query
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DemoController extends Controller
{
public function index()
{
$users = User::select("*", DB::raw('price + 500 as price_with_bonus'))->get();
dd($users);
}
}
Example 3: Conditional queries with CASE statement
You can handle conditional logic directly in your query.
$users = User::selectRaw("
id, name,
CASE
WHEN status = 'active' THEN 'Active User'
WHEN status = 'inactive' THEN 'Inactive User'
ELSE 'Unknown User'
END AS 'statusUser'
")->get();
Example 4: Some Aggregate functions used in selectRaw() query
Easily perform SQL aggregation like SUM, COUNT.
$userList = userList::selectRaw('SUM(price) as total price, COUNT(id) as total User')->where('status', 1)->first();
Example 5: Grouping Date using selectRaw() query
Use selectRaw() with groupBy for grouped query.
$history = History::selectRaw('user_id', SUM(price) AS totle_price)->groupBy('user_id')->get();
I hope this tutorial help you.