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: