Table of Contents
|1||What are helper functions ?|
|2||Why we need helper functions ?|
|3||Creating helper functions|
|4||Calling helper from controller|
Helper functions are basically reusable code , which you can use in most of the functions in controllers , models or any other file in laravel application .That piece of code that you want to use in most of the controllers .
Some functions in laravel are like you have to use in every controller , like saving an image ,some cURL request , some value converting functions (Bytes to MB,GB) or some functions when we are using apis to return json format . Liike we have some other methods of using resuable code like Traits but when you have to use these methods you first have to initialise like if we have traits , so to use them ( we have to intialize and call the method use and same in model we have to initialize in the controller ) but what if we want use that code in Blade files , that's we often sometimes to use helper functions in ou larvael application.
creating helper functions is not a very deal so here we use a helper or common function which is used in every single file in laravel. Make a folder structure like this app/Common/helper.php as shown in image.
so here we make manually a fiile name helper.php inside Common folder now we define it in autoload files inside composer.json in root directory don't replace the whole code just add the helper.php directory in autoload funtion in composer.json
code for autoload: Copy
and hit composer dump-autoload Copy
add the code which you want to use in helper.php file and use used the functions of file as helper functions here we are using a helper function named convert which converts the given size into KB,MB and GB . Copy
We can call the function in any controller as shown in given below code
code in controller: Copy