LaravelMysqlPhp

Laravel custom raw queries example

Laravel custom raw queries example

Views

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(
‘orders.id’,
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’),
‘orders.order_value’,
DB::raw(“
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’
ELSE ‘NO’
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’)
->join(‘groups’,’groups.id’,’=’,’products.group_id’)
->where(‘orders.active’, 1)
->whereRaw(‘Date(orders.timestamp_order_made) = CURDATE()’)
->orderBy(‘orders.id’,’desc’)
->get();
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

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

2 Comments

Leave a Reply

Positive SSL