In this post, we will explain how to execute MySQL query in Laravel. Sometimes, we may need to run a raw MySQL query directly in Laravel. You can easily run SQL queries in Laravel using the DB facade. In the example below, you will learn how to execute a query in Laravel.
Why Use MySQL with Laravel?
Laravel’s database capabilities are built on MySQL, a widely used relational database management system.
- Manage complex queries with ease
- Use raw SQL for custom needs
Example: Execute MySQL Query in Laravel
o execute a raw MySQL query in Laravel, you can use the DB::select()
or DB::statement()
methods. Here’s an example of how to run a query in Laravel.
Example 1: Using DB::select() for a Select Query
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class PostController extends Controller
{
public function index(Request $request)
{
$posts = DB::select('SELECT * FROM posts WHERE status = ?', ['active']);
}
}
Example 2: Using DB::statement() for an Insert Query
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class PostController extends Controller
{
public function index(Request $request)
{
DB::statement("
INSERT INTO `posts` (`id`, `title`, `body`, `created_at`, `updated_at`) VALUES (1, 'This is my post', 'This post is very meaningful', '2022-08-12 09:34:51', '2022-08-12 09:34:51');
");
}
}
Example 3: Raw UPDATE Query
DB::update('UPDATE posts SET title = ? WHERE id= ?', ['Updated post', 1]);
Example 3: Raw DELETE Query
DB::delete('DELETE FROM posts WHERE id = ?', [1]);
I hope this tutorial help you.