How to execute mysql query in laravel?

by raven_corwin , in category: PHP Frameworks , a year ago

How to execute mysql query in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , a year ago

@raven_corwin 

To execute a MySQL query in Laravel, you can use the DB facade provided by Laravel.


Here is a step-by-step guide to execute a MySQL query in Laravel:

  1. Start by importing the DB facade in your controller or model by adding the following line at the top:
1
use IlluminateSupportFacadesDB;


  1. Once you have imported the DB facade, you can use it to execute the MySQL query. Here are a few examples:
  • Select query:
1
$results = DB::select('SELECT * FROM users');


This will retrieve all the rows from the users table and store them in the $results variable.

  • Insert query:
1
DB::insert('INSERT INTO users (name, email) VALUES (?, ?)', ['John Doe', '[email protected]']);


This will insert a new row in the users table with the name and email values provided.

  • Update query:
1
DB::update('UPDATE users SET name = ? WHERE id = ?', ['Jane Doe', 1]);


This will update the name column of the row with id 1 to "Jane Doe" in the users table.

  • Delete query:
1
DB::delete('DELETE FROM users WHERE id = ?', [1]);


This will delete the row with id 1 from the users table.

  1. You can also use query builder methods provided by Laravel to build complex queries. For example:
1
2
3
4
$users = DB::table('users')
            ->where('votes', '>', 100)
            ->orderBy('name', 'desc')
            ->get();


This will retrieve all the rows from the users table where the "votes" column is greater than 100, and order them by the "name" column in descending order. The result will be stored in the $users variable.


By using the DB facade and query builder methods provided by Laravel, you can easily execute MySQL queries in your Laravel application.