Laravel MySQL Raw query example

Created at 22-Aug-2022 , By samar

Laravel MySQL Raw query example

With this article, we will examine several different instances of how to solve the "Laravel MySQL Raw query example".

Raw MySQL query are helpful when you need to write our own SQL queries. Laravel query builder has the tools we need to safely run such queries. Sometimes we have to run the Raw MySQL queries to perform some action on database then raw sql queries are very useful.
  • Raw MySQL query Example Code

    1. Raw MySQL query with selectRaw method

    $users = DB::table('users')
        ->selectRaw('count(*) as user_count')
        ->get();
    

    2. Raw MySQL query with DB::raw and DB::select

    $results = DB::select( DB::raw("SELECT * FROM users WHERE id = 1"));
    

    3. Raw MySQL query with parameter binding

    $id = Input::get("id");
    
    $results = DB::select( DB::raw("SELECT * FROM users WHERE id = :id"), array(
       'id' => $id,
     ));
    

    Import DB facade

    use Illuminate\Support\Facades\DB;
    

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.