How to run mysql query in laravel?

Member

by lizzie , in category: PHP Frameworks , 8 days ago

How to run mysql query in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 7 days ago

@lizzie 

To run a MySQL query in Laravel, you can use Laravel's built-in Eloquent ORM or the Query Builder. Here's how you can run a MySQL query using the Query Builder:

  1. First, make sure you have configured your database connection in the config/database.php file.
  2. To query the database, you can use the DB facade. Here's an example of running a simple select query:
1
2
3
use IlluminateSupportFacadesDB;

$results = DB::select('SELECT * FROM users');


  1. You can also use query builder methods to build more complex queries. Here's an example of running a select query using query builder methods:
1
2
3
4
5
$users = DB::table('users')
            ->select('name', 'email')
            ->where('status', 'active')
            ->orderBy('created_at', 'desc')
            ->get();


  1. You can also run other types of queries such as insert, update, and delete using the query builder. Here's an example of running an insert query:
1
2
3
4
5
DB::table('users')->insert([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => bcrypt('secret'),
]);


  1. Always remember to use proper parameter binding to prevent SQL injection attacks. You can use placeholders in your queries and provide the values as an array in the select, from, and other query builder methods.


These are some basic examples of how to run MySQL queries in Laravel using the Query Builder. The Eloquent ORM provides an easier and more convenient way to interact with your database, so you may want to explore that option as well.