Laravel Eloquent: How to Select Data with Raw SQL Queries

Updated: January 17, 2024 By: Guest Contributor Post a comment

Introduction

Laravel’s Eloquent ORM provides a beautiful, simple ActiveRecord implementation for working with your database. While this simplicity is one of Laravel’s strongest features, sometimes you may need to bypass the ORM and execute raw SQL queries directly.

In this tutorial, we will guide you through the process of using raw SQL queries in Laravel within Eloquent’s framework. We’ll cover some basic examples and then move onto more advanced scenarios. Whether you’re reporting complicated database data or you just prefer writing your own queries for performance reasons, this guide will help you execute raw SQL safely and efficiently in Laravel.

Getting Started with Raw SQL

Before diving into raw SQL queries, ensure that you have a Laravel project set up and that your database connection is configured correctly in your .env file.

To perform a simple raw SQL query in Laravel, you can use the DB facade. Here’s an example of how to retrieve all records from a table:

<?php

use Illuminate\Support\Facades\DB;

$results = DB::select('SELECT * FROM users');

foreach ($results as $user) {
    echo $user->name;
}

?>

This simple query will output the name of every user in your database. Remember that the DB::select() method always returns an array of stdClass objects.

Where Clauses and Parameters

To add a WHERE clause with parameters to your query, you should never directly insert variables into your query string due to the risk of SQL injection attacks. Instead, Laravel provides a method to safely bind parameters:

<?php

$results = DB::select('SELECT * FROM users WHERE active = :active', ['active' => 1]);

foreach ($results as $user) {
    echo $user->name;
}

?>

This will select only active users from your users table.

Using Raw Expressions in Query Builder

While using raw SQL queries might be necessary at times, Laravel’s query builder also allows you to use raw expressions. This way, you can insert a raw query into a fluent query builder call:

<?php

use Illuminate\Support\Facades\DB;

$users = DB::table('users')
    ->select(DB::raw('count(*) as user_count, status'))
    ->where('status', '<>', 1)
    ->groupBy('status')
    ->get();

foreach ($users as $user) {
    echo $user->status . ': ' . $user->user_count;
}

?>

This utilizes raw SQL within a query builder method chain to group users by their status and count them.

Advanced Raw Queries with Joins

As your SQL needs grow more complex, Laravel’s raw methods can still be applied. Here’s an example of an advanced join statement within Laravel:

<?php

$posts = DB::table('posts')
    ->selectRaw('posts.*, usernames.name as author_name')
    ->leftJoinSub('SELECT id, name FROM users', 'usernames', function ($join) {
        $join->on('posts.user_id', '=', 'usernames.id');
    })
    ->get();

foreach ($posts as $post) {
    echo $post->title . ' by ' . $post->author_name;
}

?>

This query joins a subquery and selects data from it, which can be incredibly powerful for generating reports or pulling together complex data.

Parametrization and Security

As you make use of raw SQL in Laravel, it’s vital to always use parameterized queries when external input is involved. This protects against SQL injection attacks, ensuring that any variables are properly escaped. Here’s an example of securely including a user’s input into your SQL query:

<?php $userId = $request->input('user_id'); $user = DB::select('SELECT * FROM users WHERE id = ?', [$userId]); if ($user) { echo $user->name; } else { echo 'User not found.'; } ?>

Using question marks ? as placeholders for parameters, Laravel will handle the escaping of data for you.

Conclusion

Throughout this tutorial, we’ve outlined various ways to use raw SQL queries within Laravel, from simple SELECT statements to more advanced join operations. The key takeaway is to always ensure that any dynamic inputs are parameterized to prevent SQL injection. While Eloquent ORM is a robust tool for database interactions, raw SQL can give you the flexibility for complex operations that fall outside of ORM capabilities.

Remember that with great power comes great responsibility. Use raw SQL queries judiciously and always prioritize the safety and integrity of your applications’ data.