How to Get Year Wise Data in Laravel?

By Hardik Savani October 13, 2021 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 and laravel 8 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 :