Click Below to subscribe

How to Get Last Week, Last Month, Last Year Records In Laravel

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries.

use App\Models\Movie;
use Carbon\Carbon; 
use Illuminate\Support\Facades\DB;

Get Last Month Records

$fromDate = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$toDate = Carbon::now()->subMonth()->endOfMonth()->toDateString();
$movies = Movie::whereBetween('created_at', [$fromDate, $toDate])->get();

Get Current Month Records

$fromDate = Carbon::now()->startOfMonth()->toDateString();
$toDate = Carbon::now()->endOfMonth()->toDateString();
$movies = Movie::whereBetween('created_at', [$fromDate, $toDate])->get();

Get Last Year Records

$movies = Movie::whereYear('created_at', Carbon::now()->subYear()->year)->get();

Get Current Year Records

$movies = Movie::whereYear('created_at', Carbon::now()->year)->get();

Get Last Week Records

$fromDate = Carbon::now()->subWeek()->startOfWeek()->toDateString();
$toDate = Carbon::now()->subWeek()->endOfWeek()->toDateString();
$movies = Movie::whereBetween('created_at', [$fromDate, $toDate])->get();

Get Current Week Records

$fromDate = Carbon::now()->startOfWeek()->toDateString();
$toDate = Carbon::now()->endOfWeek()->toDateString();
$movies = Movie::whereBetween('created_at', [$fromDate, $toDate])->get();

Get Last 7 Days Records

$fromDate = Carbon::now()->subDays(7)->toDateString();
$toDate = Carbon::now()->toDateString();
$movies = Movie::whereBetween('created_at', [$fromDate, $toDate])->get();

Get Last 30 Days Records

$fromDate = Carbon::now()->subDays(30)->toDateString();
$toDate = Carbon::now()->toDateString();
$movies = Movie::whereBetween('created_at', [$fromDate, $toDate])->get();

Count By Year

$movies = Movie::select(DB::raw('(COUNT(*)) as count'), DB::raw('YEAR(created_at) as year'))
    ->groupBy('year')
    ->get();

OR

$movies = Movie::selectRaw('(COUNT(*)) as count, YEAR(created_at) as year')
    ->groupBy('year')
    ->get();

Count By Month

$movies = Movie::select(DB::raw('(COUNT(*)) as count'), DB::raw('MONTHNAME(created_at) as month'))
    ->whereYear('created_at', Carbon::now()->year)
    ->groupBy('month')
    ->get();

OR

$movies = Movie::selectRaw('(COUNT(*)) as count, MONTHNAME(created_at) as month')
    ->whereYear('created_at', Carbon::now()->year)
    ->groupBy('month')
    ->get();

Leave Your Comment