PHP

Incorporate Raw SQL Expressions into Eloquent Queries

Extend Eloquent's capabilities by using raw SQL expressions (`DB::raw`, `selectRaw`, `whereRaw`) for complex conditions, aggregate functions, or database-specific features.

use Illuminate\Support\Facades\DB;

// Select a raw column (e.g., concatenate names)
$users = DB::table('users')
           ->selectRaw('CONCAT(first_name, " ", last_name) as full_name, email')
           ->get();

// Where raw condition
$usersByMonth = App\Models\User::whereRaw('MONTH(created_at) = ?', [10])->get();

// Order by a raw expression
$popularProducts = App\Models\Product::orderByRaw('price * quantity DESC')->take(5)->get();
How it works: While Eloquent provides a powerful fluent API, sometimes you need to drop down to raw SQL for complex queries, database-specific functions, or performance optimizations. Eloquent allows this through methods like `selectRaw()`, `whereRaw()`, and `orderByRaw()`, or by wrapping expressions in `DB::raw()`. This enables you to inject arbitrary SQL fragments into your queries, bridging the gap between Eloquent's abstraction and raw database power.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs