A Whole Host of Helpers Easily
A Whole Host of Helpers Easily
When I first came to Laravel I came across a really easy trick to use helpers.

When I first came to Laravel I found it very confusing and in my years of PHP programming I had many functions I had written that I wished to incorporate.

When was I to put them ? In controllers? It took me some time to get to grips with this and I wanted a whole host of functions to be available throughout the system.

For example i have some simple couple- frequently used - to get today's date in a few formats and the current year. Not the best example of PHP but it has worked for me for ages.

function ReturnTodaySlashes()
{
    date_default_timezone_set('Europe/London');
   $today = mktime(0, 0, 0, date("m")  , date("d"), date("Y") );
  $today = date('d/m/Y',$today );
  return $today;
};

I wanted to start my blade template off with getting this - and many other things. I wanted to simply call my function anywhere.

I had also a lot of stuff I had written, from returning a random image in a directory to neatly formatting an address.

So here is my answer.

Place all your PHP files with your functions in a directory which you can create app/Helpers. In one of my projects I have 52 files!

Now in the app/Providers directory make a new PHP file called HelperServiceProvider.php 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);

        }

    }

}

What you are doing here is telling Laravel at boot to flick through your directory and add register the  .php files.

Finally you need at add one simple line to the config/app.php file in the providers array:

'App\Providers\HelperServiceProvider'

Now all you functions will be available anywhere, and of course if you amend one or add one they are amended immediately.

What's your reaction?

Comments

https://magazine.tdbcomputing.com/assets/images/user-avatar-s.jpg

0 comment

Write the first comment for this!

Facebook Conversations

Disqus Conversations