arrow_back
Back

Laravel raw SQL: DB facade, select, and parameter binding

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Once you have configured your database connection, you may run queries using the DB facade. The DB facade provides methods for each type of query: select, update, insert, delete, and statement.

SELECT

use Illuminate\Support\Facades\DB;

$users = DB::select('SELECT * FROM users WHERE active = ?', [1]);
$posts = DB::select('SELECT * FROM posts WHERE id > ?', [2]);
$posts = DB::select('SELECT * FROM posts WHERE id > :id', ['id' => 2]);
echo $users; // We will get an array of objects (JSON)

INSERT

use Illuminate\Support\Facades\DB;

$query = DB::insert('INSERT INTO posts (title, content, created_at, updated_at) VALUES (?, ?, ?, ?)', 
['Article 1', 'Text of the article', NOW(), NOW()]);

UPDATE

use Illuminate\Support\Facades\DB; 

$query = DB::update('UPDATE posts SET created_at = ?, updated_at = ? WHERE created_at IS NULL', 
[NOW(), NOW()]);

DELETE

use Illuminate\Support\Facades\DB; 

$query = DB::delete("DELETE FROM posts WHERE id = ?", [4]);

STATEMENT

use Illuminate\Support\Facades\DB; 

$query = DB::statement('DROP TABLE users');

Transactions

DB::transaction(function() {
    // Queries...
});

Or:

DB::beginTransaction();

try {
    // Queries...
    DB::commit();
} catch (Exception $e) {
    DB::rollBack();
}

Listen to all SQL queries

app/Providers/AppServiceProvider.php, boot() function:

DB::listen(function($query) {
    dump($query->sql, $query->bindings);
});
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Laravel Query Builder: fluent SQL, joins, and conditions

arrow_forward