How to write raw query in laravel?

Member

by lew , in category: PHP Frameworks , 4 months ago

How to write raw query in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 4 months ago

@lew 

To write a raw query in Laravel, you can use the DB facade provided by Laravel. Here is an example of how you can write a raw query in Laravel:

1
2
3
4
5
6
7
use IlluminateSupportFacadesDB;

$results = DB::select('SELECT * FROM users WHERE id = ? LIMIT 1', [1]);

foreach ($results as $result) {
    // Do something with the result
}


In this example, we are using the select method provided by the DB facade to execute a raw SQL query. The first argument is the raw SQL query, and the second argument is an array of bindings that will be escaped and injected into the query.


You can also use other methods provided by the DB facade, such as insert, update, delete, etc., to execute different types of raw queries in Laravel.