Home Laravel Laravel custom raw queries example

Laravel custom raw queries example

by therichpost
Laravel 7.2 routing with route group auth guard check with prefix

Hello to all, welcome to the richpost.com. In this post, I will tell you, how to do raw queries in laravel? Laravel is one of the top Mvc php framework. Sometime we do custom queries in simple mysql in core php but In laravel there are some tricky ways to do this.

Here is the working Laravel custom raw queries example and this query we are getting data in json format:

$orders = Order::select(
DB::raw(‘DATE_FORMAT(orders.timestamp_order_made, “%m/%d/%Y”) as order_date’),
DB::raw(‘DATE_FORMAT(orders.timestamp_order_made, “%h:%i %p”) as order_time’),
CASE orders.status
WHEN ‘1’ THEN ‘Order Placed’
WHEN ‘2’ THEN ‘Allocated’
WHEN ‘3’ THEN ‘Rejected’
WHEN ‘4’ THEN ‘Failure’
WHEN ‘5’ THEN ‘Accepted’
WHEN ‘6’ THEN ‘Delivered’
WHEN ‘7’ THEN ‘Accepted by dispensary’
WHEN ‘8’ THEN ‘Pickup at dispensary’
END as order_status
DB::raw(“CONCAT_WS(‘ ‘,users.first_name, users.last_name) AS customer_name”),
‘groups.name as group_name’
->join(‘users’, ‘users.id’,’=’,’orders.user_id’)
->join(‘order_products’, ‘order_products.order_id’,’=’,’orders.id’)
->join(‘products’, ‘products.id’,’=’,’order_products.product_id’)
->where(‘orders.active’, 1)
->whereRaw(‘Date(orders.timestamp_order_made) = CURDATE()’)
return response()->json([‘data’ => $orders], 200);

In this query, I am giving the example for DATE_FORMAT, Case statements, Concat.

There are so many code tricks in laravel and i will let you know all. Please do comment if you any query related to this post. Thank you. Therichpost.com

You may also like


rohil March 22, 2018 - 7:50 am

good example for case thank you

therichpost March 22, 2018 - 7:50 am

welcome rohil


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.