How to Use DB Raw Query in Laravel Explained Tutorial

Reading Time: 5 minutes
918 Views

Inside this article we will see the concept i.e How to Use DB Raw Query in Laravel Explained Tutorial. Article contains the classified information about How To execute Raw Queries in Laravel.

If you are looking to execute select query with MySQL cases, Count query, Join query, Where conditional query, etc using laravel raw queries logics then this article will help you a lot for this.

Here we will see these:

  • DB Raw with Select Clause Query in Laravel
  • DB Raw with Count Query in Laravel
  • DB Raw with Join Query in Laravel
  • DB Raw with Where Condition Query in Laravel

Read More: Laravel How To Get Min Value of Column Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

What is DB Facade in Laravel?

In a Laravel application, a facade is a class that provides access to an object from the container. Once you have configured your database connection, you may run queries using the DB facade. The DB facade provides methods for each type of query: select , update , insert , delete , and statement.

Before using DB facade, you need to import

use Illuminate\Support\Facades\DB;

Methods Available:

DB::select()

DB::insert()

DB::update()

DB::delete()

Read More: Laravel How To Get Max Value of Column Tutorial

Example #1: DB Raw with Select Clause Query in Laravel

We are considering a Test Controller to understand this concept.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\DB;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $users = User::select(DB::raw("
                          name,
                          email,
                          (CASE WHEN (type = 1) THEN 'Admin' ELSE 'User' END) as user_type"))
                     ->take(3)
                     ->get();
  
        dd($users);
    }
}

Example #2: DB Raw with Count Query in Laravel

Again, we are considering a Test Controller to understand this concept.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\DB;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $users = User::select(DB::raw('type, count(*) as user_count'))
                     ->groupBy('type')
                     ->get();
  
        dd($users);
    }
}

Example #3: DB Raw with Join Query in Laravel

Read More: How To Create Arithmetic Calculator Using jQuery

Again, we are considering the same controller as above i.e Test Controller to understand this concept.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $data = Product::select("products.*", "product_stock.quantity_group")
              ->join(DB::raw("(SELECT 
                    product_stock.id_product,
                    GROUP_CONCAT(product_stock.quantity) as quantity_group
                  FROM product_stock
                    GROUP BY product_stock.id_product
                  ) as product_stock"),function($join){
                    $join->on("product_stock.id_product","=","products.id");
              })
              ->groupBy("products.id")
              ->get();
  
        dd($data);
    }
}

Example #4: DB Raw with Where Condition Query in Laravel

Again, we are considering the same controller as above i.e Test Controller to understand this concept.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
  
class TestController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $data = Order::where('id', DB::raw("(select max(`id`) from orders)"))->get();
  
        dd($data);
    }
}

Here, we have explained all different different cases by which you can use DB::raw() method to run your queries inside laravel application.

Read More: How To Disable Specific Dates In jQuery Datepicker Tutorial

We hope this article helped you to learn How to Use DB Raw Query in Laravel Explained Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.