How to Use and Execute Raw SQL in Laravel Application
In this tutorial, I will show you how to execute raw SQL queries in Laravel. You know that if you use raw SQL query then it will enhance your query performance as well as application performance.
So this laravel execute raw query example, you will learn how to run raw query in laravel 9 application. So if you don't know how to run raw SQL in Laravel, then this example is for you.
Suppose you want to use select query. Then write your query like that:
$users = \DB::select('SELECT * from users');
Now we can write like:
$query = "select A.*,C.Name AS Criteria,B.Name AS SubCriteria,D.Name AS SubSubCriteria from AssignKPI A INNER JOIN SubCriterias B ON A.KPIID = B.SubCriteriaID INNER JOIN Criterias C ON C.CriteriaID = B.CriteriaID LEFT JOIN SubSubCriterias D ON D.SubCriteriaID = B.SubCriteriaID where A.UserID = '24221'"; $result = DB::select(DB::raw($query));
Another example like:
$users = \DB::select('SELECT * from users WHERE email = ?', [$request->email]);
You can insert with raw SQL query in Laravel like:
$users = \DB::insert('INSERT into users (name, email) VALUES (?, ?)', [$request->name, $request->email]);
Hope it can help you.