jim1506
1 week ago

A Helpers Tip

Posted 1 week ago by jim1506

On larger projects I tend to have a load of .php files in a directory Helpers. I like to keep them separate so I can easily find something or add.

So I add a HelpersServiceProvider.php in the Providers directory with the following code:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
  /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }
    }
}

It will register all the php files in the directory even if you add or whatever.

Then just add in config/app under Providers

  'App\Providers\HelperServiceProvider',

and it just does it for you.

So you can now call a function in any of your helpers anywhere.

Please sign in or create an account to participate in this conversation.