How to create custom helper functions in Laravel
Tags: laravel, php, webdev, beginners
Published: 2022-04-27 18:35:00

Laravel provides us with many built-in helper functions that you can call anywhere within your application. They make your workflow convenient for working with arrays & objects, paths, strings, URLs, and other types.

Although many helper functions are defined in the laravel core, you can define your helper functions in the laravel to avoid repeating the same code. It ensures the better maintainability of your application.

Laravel and PHP also provide some basic functions that can be called anywhere, however, there are some times we might need to write our own custom functions that we will need both in the controller and in the views or other parts of our app.

Let’s walk through how you can create your custom Laravel helper functions.

## How to create custom helper functions in Laravel
The first scenario you might want to include your helper functions is within the context of a Laravel application. Depending on your preference, you can organize your helper file(s) location however you want. However, here are a few suggested locations:

- **app/helpers.php**
- **app/Http/helpers.php**

I prefer to keep mine in app/helpers.php at the root of the application namespace.

Let’s create a file helpers.php inside /app folder.

Open /app/helpers.php file and write this code into it.

```
<?php

if(!function_exists("generateUniqueToken")){

    function generateUniqueToken($size = 10,$table = null,$column = null)
    {
	     $token = str_random($size);

	     if($table && \DB::table($table)->where($column,$token)->count()){
		      generateUniqueToken($size, $table, $column);
	     }

	     return $token;
    }
}
```
Here, we have defined a simple essential function to generate a unique token.

### Autoloading
To use your PHP helper functions, you need to load them into your program at runtime. In the early days of my career, it wasn’t uncommon to see this kind of code at the top of a file:
```
require_once ROOT . '/helpers.php';
```
PHP functions cannot be autoloaded. However, we have a better solution through Composer than using require or require_once.

If you create a new Laravel project, you will see an autoload and autoload-dev keys in the composer.json file:
```
"autoload": {
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
```
If you want to add a helpers file, the composer has a files key (which is an array of file paths) that you can define inside of autoload:
```
"autoload": {
    "files": [
        "app/helpers.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
```
Once you add a new path to the files array, you need to dump the autoloader:
```
cd <Go to your Laravel App Path> && composer dump-autoload
```
Now on every request, the helpers.php file will be loaded automatically because Laravel requires Composer’s autoloader in public/index.php:
```
require __DIR__.'/../vendor/autoload.php';
```
If you don't like keeping your helpers.php file in your app directory (because it's not a PSR-4 namespaced class file), you can do what the laravel.com the website does: stores the helpers.php in the bootstrap directory. Remember to set it in your composer.json file:
```
"files": [
    "bootstrap/helpers.php"
]
```

## Usage Helper Function
Now, we will see how to use the custom helper function in an application.
### Using into View
```
<div>
     @php
        $token = generateUniqueToken(32, '<Table-Name>','<Column-Name>');
     @endphp

        {{ $token }}
 </div>
```
### Using into Controller
```
$token = generateUniqueToken(32, '<Table-Name>','<Column-Name>');
```
### Using Closure Routes
```
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('/', function () {
    $token = generateUniqueToken(32, '<Table-Name>','<Column-Name>');
    
    echo $token;
});
```
Thank you for reading this blog.