How To Get Current Year Wise Record in Laravel 11 | websolutioncode.com
How To Get Current Year Wise Record in Laravel 11 | websolutioncode.com

How To Get Current Year Wise data in Laravel 11?

Introduction: Retrieving data based on specific criteria is a common task in web development. In Laravel, a popular PHP framework, getting current year wise data can be quite straightforward if you know the right approach. In this tutorial, we’ll walk through the process step by step, providing clear explanations and practical code examples along the way.

Step 1:

Setup Laravel Project Firstly, ensure you have Laravel installed on your system. If not, you can install it via Composer using the following command:

composer create-project --prefer-dist laravel/laravel project-name

Navigate to your project directory and start a local development server using

php artisan serve

Step 2:

Database Setup For this tutorial, we’ll assume you already have a database set up with relevant data. If not, create a migration to generate a table with sample data. Let’s say we have a “sales” table with columns: id, amount, and created_at.

php artisan make:migration create_sales_table

In the generated migration file, define the schema for the “sales” table:

Schema::create('sales', function (Blueprint $table) {
$table->id();
$table->decimal('amount', 8, 2);
$table->timestamps();
});

Don’t forget to run the migration to create the table:

php artisan migrate

Step 3:

Retrieve Year Wise Data Now, let’s focus on retrieving data for a specific year. We’ll use Laravel’s Eloquent ORM for this purpose. In your controller or wherever appropriate, write a method to fetch data for a given year:

use App\Models\Sale;
use Illuminate\Http\Request;

public function getYearlyData(Request $request)
{
$year = $request->input('year');

$yearlyData = Sale::whereYear('created_at', $year)->get();

return response()->json($yearlyData);
}

This method takes a year as input, queries the “sales” table for records matching that year, and returns the result in JSON format.

Step 4:

Route Setup Define a route to access this method. Open the “routes/web.php” file and add:

use App\Http\Controllers\SaleController;

Route::get('/sales/yearly', [SaleController::class, 'getYearlyData']);

Step 5:

Test the Endpoint You can now test the endpoint using tools like Postman or simply by sending a GET request with the desired year parameter:

GET http://localhost:8000/sales/yearly?year=2023

Replace “2023” with the year you want to retrieve data for. You should receive a JSON response containing sales data for that year.

Conclusion:

In this tutorial, we’ve covered how to current year wise data in Laravel 11 using Eloquent ORM. By following these steps, you can efficiently fetch data based on specific criteria in your Laravel applications. Experiment with different queries and enhance your understanding of Laravel’s powerful features. Happy coding!