How to use DB Raw Query with an example in Laravel?

08-Oct-2022

.

Admin

How to use DB Raw Query with an example in Laravel?

Hello Friends,

Now, let's see a tutorial on how to use db raw query with an example in laravel. This post will give you a simple example of how to use a db raw query in laravel. This article goes into detail on how to write a db raw query in laravel. This tutorial will give you a simple example of how to execute db raw sql queries in laravel. you will do the following things for the db row 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