How to Use DB Facade in Laravel: Simple Guide
In Laravel, use the
DB facade to run database queries directly by calling methods like select, insert, update, and delete. Import DB with use Illuminate\Support\Facades\DB; and then call its methods to interact with your database.Syntax
The DB facade provides static methods to perform database operations. Common methods include:
DB::select($query, $bindings)- Run a select query and get results.DB::insert($query, $bindings)- Insert records.DB::update($query, $bindings)- Update records.DB::delete($query, $bindings)- Delete records.DB::statement($query, $bindings)- Run a general SQL statement.
Each method accepts a raw SQL query string and an optional array of bindings to safely insert variables.
php
use Illuminate\Support\Facades\DB; // Select example $users = DB::select('select * from users where active = ?', [1]); // Insert example DB::insert('insert into users (name, email) values (?, ?)', ['John', 'john@example.com']); // Update example DB::update('update users set votes = 100 where name = ?', ['John']); // Delete example DB::delete('delete from users where name = ?', ['John']);
Example
This example shows how to fetch active users from the database using the DB facade and display their names.
php
<?php use Illuminate\Support\Facades\DB; Route::get('/active-users', function () { $users = DB::select('select * from users where active = ?', [1]); foreach ($users as $user) { echo $user->name . '<br>'; } });
Output
Alice<br>Bob<br>Charlie<br>
Common Pitfalls
Common mistakes when using the DB facade include:
- Not importing the
DBfacade withuse Illuminate\Support\Facades\DB;. - Forgetting to use parameter bindings, which can lead to SQL injection vulnerabilities.
- Using raw queries when Eloquent or the query builder would be safer and easier.
- Not handling empty results or exceptions.
php
use Illuminate\Support\Facades\DB; // Wrong: vulnerable to SQL injection $name = "O'Reilly"; DB::select("select * from users where name = '$name'"); // Right: safe with bindings DB::select('select * from users where name = ?', [$name]);
Quick Reference
| Method | Description |
|---|---|
| DB::select() | Run a select query and return results. |
| DB::insert() | Insert new records into the database. |
| DB::update() | Update existing records. |
| DB::delete() | Delete records from the database. |
| DB::statement() | Run a general SQL statement. |
Key Takeaways
Always import the DB facade before using it with 'use Illuminate\Support\Facades\DB;'.
Use parameter bindings to protect against SQL injection.
DB facade methods let you run raw SQL queries easily in Laravel.
Prefer Eloquent or query builder for complex queries and better readability.
Handle query results and exceptions to avoid runtime errors.