0

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?

Ashu
  • 1
  • 1
  • 2
  • they are loaded with a service provider or in a composer.json autoloader depending on if its a custom helper or a default helper – Gert B. Aug 04 '22 at 11:59
  • "I know how to create [my] own custom function file and make it available globally using [the] compose[r].json file" So why do you think that the built-in functions would work any differently? https://github.com/laravel/framework/blob/v8.52.0/composer.json#L101 – miken32 Aug 04 '22 at 16:58
  • I was confused since I was not able to find that in main composer file. Its autoload is located in laravel/framework. I got the answer – Ashu Aug 04 '22 at 17:06

2 Answers2

1

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.

mrhn
  • 17,961
  • 4
  • 27
  • 46
  • I have found that file .. thanks – Ashu Aug 04 '22 at 17:01
  • So this means we can have any number of composer files and anything defined in it i.e autoload will be discoverd by laravel .. This is off topic but just wanted to confirm – Ashu Aug 04 '22 at 17:03
  • One in each project and one in each package, but if you see the autoloader structure in composer.json, you can see it can take multiple autoloaded file locations – mrhn Aug 04 '22 at 18:29
0

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.

kapitan
  • 2,008
  • 3
  • 20
  • 26