How to Execute MySQL Query in Laravel - TechvBlogs

How to Execute MySQL Query in Laravel

In this article, You will learn How to run mysql query into Laravel.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

2 months ago

TechvBlogs - Google News

At times, there is a need to execute raw MySQL queries directly in Laravel, such as when copying data from one table to another. In this example, I will demonstrate how you can utilize the DB statement to run SQL queries in Laravel. This approach is useful for handling specific tasks that may not have a dedicated Laravel Eloquent method. Let's explore how to execute SQL queries in Laravel using the DB statement.

Execute MySQL Query in Laravel Example

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use DB;
     
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
          
        DB::statement("
            INSERT INTO `posts` (`id`, `title`, `body`, `created_at`, `updated_at`, `slug`) VALUES (NULL, 'Demo Title', 'This is body', '2023-04-26 09:34:51', '2023-04-26 09:34:51', 'demo-body');
        ");
  
    }
}

Thank you for reading this guide!

Comments (0)

Comment


Note: All Input Fields are required.