Categories

Sunday, December 22, 2024
#919814419350 therichposts@gmail.com
LaravelMysqlPhp

Laravel custom raw queries example

Laravel 7.2 routing with route group auth guard check with prefix

Laravel custom raw queries example

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

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

2 Comments

Leave a Reply

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