Raw expressions let you write database commands exactly as you want without Laravel changing them. This helps when you need special SQL parts that Laravel doesn't handle automatically.
0
0
Raw expressions in Laravel
Introduction
When you want to use SQL functions like NOW() or COUNT() directly in your query.
When you need to write a custom SQL snippet that Laravel's query builder can't create.
When you want to avoid Laravel escaping or modifying a part of your query.
When you want to use database-specific commands or operators not supported by Laravel.
Syntax
Laravel
DB::raw('your SQL expression here')Use DB::raw() inside Laravel's query builder to insert raw SQL.
Be careful to avoid SQL injection by not inserting user input directly inside raw expressions.
Examples
This counts all users and returns the count with the name
user_count.Laravel
DB::table('users')->select(DB::raw('COUNT(*) as user_count'))->get();
This uses a raw WHERE clause to get orders with price greater than 100.
Laravel
DB::table('orders')->whereRaw('price > 100')->get();
This selects product names and adds the current database time as
current_time.Laravel
DB::table('products')->select('name', DB::raw('NOW() as current_time'))->get();
Sample Program
This example gets all users and shows their names plus the uppercase version using a raw SQL function UPPER(). It prints each user's name and uppercase name.
Laravel
<?php use Illuminate\Support\Facades\DB; $results = DB::table('users') ->select('name', DB::raw('UPPER(name) as uppercase_name')) ->get(); foreach ($results as $user) { echo "Name: {$user->name}, Uppercase: {$user->uppercase_name}\n"; }
OutputSuccess
Important Notes
Always sanitize or avoid inserting user input directly into raw expressions to prevent SQL injection.
Raw expressions bypass Laravel's query builder protections, so use them only when necessary.
You can use raw expressions in select, where, orderBy, and other query builder methods.
Summary
Raw expressions let you write exact SQL inside Laravel queries.
Use DB::raw() to add raw SQL safely in your queries.
Be careful with raw expressions to avoid security risks.