Laravel Use DB Raw Query With Example

Oct 08, 2022 . Admin



Hello Friends,

In this example, I will show you laravel use db raw query with an example. This post will give you a simple example of how to use a db raw query with an example in laravel. this example will help you how to execute db raw sql queries in laravel. you can understand the concept of how to run a db raw sql query in laravel. Here, Creating a basic example of a db raw query with a code example in laravel.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

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 a database table, use the laravel eloquent methods.

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

$users = User::get();

To 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

When you write a query in your controller using a 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: 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

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

You can write as follow:

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

I hope it can help you...

#Laravel