Laravel How to Create Custom Helper Functions in Laravel

Hello Artisan, today I'll show you how to create a custom helper function in Laravel. Helper functions used to make our code more readable and concise. One of the great advantage of helper function is that we can use it anywhere we like. Either it's a blade file or controller, no matter what. So, let's see how we can easily create a helper function in our project.

Note: Tested on Laravel 10.8

Table of Contents

  1. Setup and Usage of Helper Function
  2. Output

Setup and Usage of Helper Function

At first we'll create file under app/Helper directory called Helper.php. Then we'll write a function called currentYear() in this file like below

app/Helper/Helper.php
<?php

function currentYear(): string
{
    return date('Y');
}

And in the turn, whenever we call this function, It'll give us the current year as a output. We can use it anywhere we want by calling currentYear(). So, as for example let's create a below route in routes/web.php.

web.php
Route::get('/year', function () {
    dd(currentYear());
});

Output

Now if we visit http://127.0.0.1:8000/year this page then we can see the below output

That's it for today. Hope this tutorial will be helpful in your upcoming projects. You can also download this tutorial from GitHub. Thanks for reading. ๐Ÿ™‚