How to create helper methods on Laravel, not a facade

I read a lot of questions on how to create helper methods in Laravel 5.1. But I do not want to achieve this through the Facade.

HelperClass::methodName(); 

I want helper methods just like helper methods on these Laravel methods , like:

 myCustomMethod(); 

I do not want to make it a facade. Is it possible? How?

+7
source share
2 answers

If you want to go to the "Laravel way", you can create the helpers.php file using custom helpers:

 if (! function_exists('myCustomHelper')) { function myCustomHelper() { return 'Hey, it\ working!'; } } 

Then put this file in some directory, add this directory to the startup section of the composer.json application:

 "autoload": { .... "files": [ "app/someFolder/helpers.php" ] }, 

Run the composer dumpauto and your helpers will work through all applications, for example, Laravel.

If you want more examples, take a look at the original Laravel helpers in /vendor/laravel/framework/Illuminate/Support/helpers.php

+3
source

To start, I created a folder in my application directory called Helpers . Then, in the Helpers folder, I added files for the features I wanted to add. Having a folder with several files avoids the fact that one large file becomes too long and unmanageable.

Then I created HelperServiceProvider.php by running the artisan command:

artisan make:provider HelperServiceProvider In the register method, I added this fragment

 public function register() { foreach (glob(app_path().'/Helpers/*.php') as $filename){ require_once($filename); } } 

finally register the service provider in config/app.php in the providers array

 'providers' => [ 'App\Providers\HelperServiceProvider', ] 

After that, you need to run composer dump-autoload and your changes will be visible in Laravel.

any file in the Helpers directory is now loaded and ready to use.

Hope it works!

+4
source

All Articles