Laravel MySQL Raw query example

Updated at 23-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