Home > Mobile >  How laravel's helper functions are available globally in every file?
How laravel's helper functions are available globally in every file?

Time:08-05

I have just started exploring laravel but I have one confusion . I know how to create own custom function file and make it available globally using compose.json file but I was trying to figure out how laravel's helper function like route() , view() are accessible without including there source file and I can't find any auto discovery in composer.json file neither in any Service Provider .

PS : I have only checked in in Providers/ Directory.

Can anyone tell me how this thing works?

CodePudding user response:

Through composer Laravel has defined which files should be autoloaded. With the line in the composer.json file in Laravel/framework it specifies what should be autoloaded.

It loads the following file.

You can create similar autoloaders if you prefer, but having to much logic in such helpers could easily become an anti pattern. As the logic, is a little more hidden than class based logic, when people have to look through your projet.

CodePudding user response:

On your composer.json file on the root directory of your laravel app, look for the entry autoload.

This means all methods on those directories are autoloaded.

That is why if you have (newly) created a method / function within those directory and it doesn't work (or not found) as expected, you need to run composer dump-autoload to make sure that everything has been loaded.

That's also where I put my custom helper file:

"files": [
  "app/Helpers/helpers.php"
]

All function here will then be available on all controllers, traits and views.

  • Related