How to create custom helper function in laravel ?


Helper functions are the global functions that are accessible everywhere in the application. Laravel provides elegant way to define functions that are used frequently in a application. After defining a function as helper, we can access it any where inside the application. There are some such builtin functions. We can see those functions in laravel official documentation.

https://laravel.com/docs/5.7/helpers#available-methods 

When we need to perform some common operation like creating a slug from string frequently in multiple places inside laravel application, then it’s better to create a helper function and call it whenever necessary.

At first we have to create a php file that contains such type of functions. Let’s create a file inside app/Helper/ folder which is recommended normally.

helper.php

Here, at first we checked getSlug function exists or not because we can’t create a function that is already made available in laravel. The above function returns a slug of a string. Some example output of above function are,

Input: Test String

Output: test-string

Input: Stack Learning

Output: stack-learning

Display custom error message in Laravel


In order to use above function everywhere inside laravel application, we have to register the function to auto load in composer like this:

After this we have to regenerate autoload files with following console command

Now, we can use the getSlug function everywhere in our laravel application.


When we separate the common function, it will reduce the code duplication problem. These functions are like globle variables in php. We can define a function and then easily access the function anywhere in the application. Using such function provides a lot of advantages. When we want to change common functionality then one change in the helper function will change the functionality in every place where we have used the function. We can say such functions as reusable block of code easily accessible in the application.


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

Your email address will not be published. Required fields are marked *