How to Use DB Raw Query in Laravel

How to Use DB Raw Query in Laravel

Laravel db raw query example. In this tutorial, you will learn how to use db raw query in laravel. as well as learn how to use DB::raw() with join() function of laravel eloquent. 

Note that, Using the DB::raw() eloquent method, you can add subquery in laravel queries.

If you may want to insert, retrieve, update, and delete data into database table, use the laravel eloquent methods.

For retrieve all data from the database table, you can use the following query:

$users = User::get();

For delete data from the database table, you can use the following query:

$users = User::where('columnname', columnvalue)->delete();

Example 1: DB raw With Select Clause Query in laravel

When you write query in your controller using model or query builder and may need to use a raw expression in a query.

You can write as follow:

$users = User::select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

Example 2: Laravel DB Raw Query With Join

How to write db raw query with laravel joins.

You can write as follow:

$data = DB::table("products")

  ->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();



print_r($data);

Example 3: Using DB Raw Get Max Value in Laravel Query

Using the db raw, you can get max value from db.

You can write as follow:

\DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();

Recommended Laravel Posts

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *