To perform raw SQL queries with Eloquent in Laravel, you can make use of the DB
facade provided by Laravel.
Here are the steps to perform raw SQL queries using Eloquent:
Import the DB
facade at the top of your file:
use Illuminate\Support\Facades\DB;
You can then use the DB
facade to execute raw SQL queries by utilizing the select
, insert
, update
, delete
, or statement
methods.
a) Select Query:
$users = DB::select('SELECT * FROM users WHERE active = ?', [1]);
b) Insert Query:
$inserted = DB::insert('INSERT INTO users (name, email) VALUES (?, ?)', ['John Doe', '[email protected]']);
c) Update Query:
$updated = DB::update('UPDATE users SET active = ?', [0]);
d) Delete Query:
$deleted = DB::delete('DELETE FROM users WHERE active = ?', [0]);
e) Statement:
$result = DB::statement('TRUNCATE TABLE users');
You can also use bindings to prevent SQL injection by passing an array of values as the second argument to the methods. Laravel will automatically sanitize the values.
Example:
$name = 'John Doe';
$users = DB::select('SELECT * FROM users WHERE name = :name', ['name' => $name]);
By using the DB
facade, you can perform raw SQL queries in Laravel while leveraging the benefits of Eloquent's query builder pattern and database abstraction.