How to Get Year Wise Data in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

This example is focused on laravel get year wise data. Here you will learn laravel get year with count of records. i explained simply about how to get year wise data in laravel. In this article, we will implement a get all years records with count in laravel. Let's see bellow example laravel get year wise data.

we can get data year with count in laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 application.

Here, i will give you very simple example of how to get year wise data in laravel. we will use whereBetween() and Carbon in this example.

I have one created items table that structure as bellow you can see.

items table:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;

use App\Models\Item;

use Carbon\Carbon;

use DB;

class ITSController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$items = Item::select(

DB::raw("(COUNT(*)) as count"),

DB::raw("YEAR(created_at) as year")

)

->orderBy('created_at', 'DESC')

->groupBy('year')

->get();

dd($items);

}

}

Output:

Array

(

[0] => Array

(

[count] => 4

[year] => 2021

)

[1] => Array

(

[count] => 6

[year] => 2020

)

[2] => Array

(

[count] => 2

[year] => 2019

)

)

I hope it can help you...

Tags :
Shares