PHP

Integrate Complex SQL with Eloquent using `DB::raw`

Learn to embed raw SQL expressions and functions directly into your Laravel Eloquent queries using `DB::raw`, for advanced database operations.

use App\Models\Order;
use Illuminate\Support\Facades\DB;

// Example 1: Selecting a calculated column
$ordersWithTotal = Order::select('id', 'customer_id', DB::raw('price * quantity AS total_amount'))
                            ->get();

foreach ($ordersWithTotal as $order) {
    echo "Order ID: " . $order->id . ", Total Amount: " . $order->total_amount . "
";
}

// Example 2: Using raw expressions in a WHERE clause
$recentOrders = Order::where(DB::raw('DATE(created_at)'), '=', DB::raw('CURDATE()'))
                        ->get();

foreach ($recentOrders as $order) {
    echo "Recent Order ID: " . $order->id . "
";
}

// Example 3: Grouping by a raw expression
$ordersPerDay = Order::select(DB::raw('DATE(created_at) as order_date'), DB::raw('COUNT(*) as total_orders'))
                        ->groupBy(DB::raw('DATE(created_at)'))
                        ->orderBy('order_date', 'desc')
                        ->get();

foreach ($ordersPerDay as $day) {
    echo "Date: " . $day->order_date . ", Orders: " . $day->total_orders . "
";
}
How it works: While Eloquent's fluent syntax covers most query needs, `DB::raw` allows you to inject arbitrary SQL expressions directly into your queries. This is invaluable when you need to use database-specific functions, perform complex calculations, or employ operations that aren't natively supported by Eloquent's builder. It provides a powerful bridge between Eloquent and the underlying SQL database, enabling advanced query customization.

Need help integrating this into your project?

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

Hire DigitalCodeLabs