In today’s tutorial, we are showing how to get last week’s data in Laravel using Carbon. In other words, you need to pull all the orders received in the last week. In this case, last week does not mean the last 7 days, but it’s a full week starting from Monday to Sunday. For example, if you pull the data on June 7, 2022, the last week will be May 30, 2022, to June 5, 2022.
Hope you understand what we are going to achieve in this post. Instead of using raw PHP date functions, we will use we use Carbon – A simple PHP API extension for DateTime, which is inherited from the PHP DateTime class.
As an illustration, we have a table filled with orders received from our valuable customers. We need to show all the orders received last week in the dashboard to make it easy for the finance team.
In the code, we will have the below lines.
use Carbon\Carbon; // Today 7 Jun 2022 $startWeek = Carbon::now()->subWeek()->startOfWeek(); // 30 May 2022 $endWeek = Carbon::now()->subWeek()->endOfWeek(); // 5 June 2022 $orders = Order::query()->whereBetween('created_at',[ $startWeek,$endWeek ])->get(); dd($orders);
This will print the last week’s records.
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply