Home Database Create Custom Helper Functions in Laravel

Create Custom Helper Functions in Laravel

4225
Create custom helper functions in Laravel 5

Laravel Helper is a simple PHP global function that you can use to save your time in writing some repetitive codes. Laravel provides more than hundred helper functions to speed up the development process. The helper function can be called from anywhere inside an application. So, it helps to remove code repetitions. Example of commonly used helper functions.

Example of Helper function

Let’s create a slug where each string is separated by dash (-) from a post title. In PHP, you have to write the following code

$title = 'This is my first blog post';

$slug = implode('-', explode(' ', strtolower($title)));

//output: this-is-my-first-blog-post

Using the Laravel helper function, you can simply write the following

$title = 'This is my first blog post';

$slug = str_slug($title, '-');

//output: this-is-my-first-blog-post

Method 1: Creating Laravel custom helper function using Composer

Step 1: Create a new directory inside App directory as Helpers. Inside Helpers directory, create a called helpers.php. Add your helper functions in this file.

<?php 

namespace App\Helpers;

/** php function to generate random string of given length **/

function generateRandomString($length = 8) {

$characters = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ';

$charactersLength = strlen($characters);

$randomString = '';

for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
}

return $randomString;}

Step 2:
Laravel won’t recognize our file so we need to autoload it. Autoload helpers.php file using composer.json. Inside composer.json file, add lines as shown:

creating-custom-helpers-in-laravel-5_6

Step 3:
Now, run the dump-autoload command and you can generateRandomString() function from anywhere in your application.

composer dump-autoload

Using our custom Helper Function

We can call our helper function from anywhere. For example, let’s call it from route file

Route::get('/generate-random-string', function () {
    return generateRandomString(8);
});

It will give output like: V4Z8TYQF

Method 2: Creating Laravel custom helper function using Service Provider

Step 1:

Create a directory named Helpers inside the App directory. In this directory, you will be adding your helper functions files. Writing a separate helper function will be good if you want to break down the large single helper functions file into smaller manageable files. For those that may have a lot of helper functions, multiple file organization is a must. This solution is essential.

Let’s create a helper function that generates a random string of 8 characters. For this, create a file named RandomString.php inside App/Helpers directory and add the following code inside it.

<?php

namespace App\Helpers;

class RandomString {

    function generate($length = 8) {

        $characters = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ';

        $charactersLength = strlen($characters);

        $randomString = '';

        for ($i = 0; $i < $length; $i++) { 
            $randomString .= $characters[rand(0, $charactersLength - 1)]; 
        } 
        
        return $randomString;
    }
} 

Step 2:

Go to your command line and create HelperServiceProvider.php with the following code.

php artisan make:provider HelperServiceProvider

creating-service-provider-in-laravel

This will create a file named HelperServiceProvider.php inside App/Providers directory which looks like below:

helperserviceprovider

Step 3:

The register method is used to register your dependencies, and we’ve exactly done that. Let’s add some code in the register function to load the helpers.

public function register() {
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
    }
}

Step 4:

Register your service provider in config/app.php.  Find “providers” array and add the following code at the bottom of providers.

App\Providers\HelperServiceProvider::class,

add service provider in provider array

Also, add Alias as below:

'RandomString' = App\Helpers\RandomString::class,

Route::get('/generate-random-string', function () {
    return RandomString::generate (8);
});

This will out a random string like: 9E6X87LS

Using Models in Helper function

Using the Models in Helper function is quite easy. We can use any model by importing it in the helper function.  For Example, using User.php model as:

namespace App\Helpers;

use App\Models\User;

function getUserById($id) {    
    return User::find($id);
}

Conclusion
The above process shows how to create custom helper functions and how it helps to remove code repetitions. We can create as many helper functions as we want.

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.