Create a Custom Helpers Class

If you have some functions you may want to reuse or just want to keep your Controllers from getting bloated, you can create one or more Helpers classes for that.

Unfortunately a custom Helpers class can't be created as easily as a Model or Controller, but it's not very hard either.

How to create a custom Helpers class with Composer autoload

This is the way I currently create and use Helpers classes and it works great, even though it can take you a couple of minutes to set up a class.

First you have to create a Helpers.php file in app/Http.

The file should look like this:

<?php

namespace App\Http;

class Helpers
{
	public function doSomething()
	{
		// Do something here
	}
}

Then head over to composer.json and add "files": ["app/Http/helpers.php"] in the autoload block. Your composer autoload block should look like this:

"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/Helper.php"
        ]
    },

Now you have to run composer dump-autoload from the command line and you're done.

You can use the new Helpers class by including it with use:

<?php

namespace App\Http\Controllers;
use App\Helpers;

class SomeController extends Controller
{
	public function store(Helpers $helpers)
	{
		$helpers->doSomething();
	}
}

And that's all. Now you can use your Helpers class or even create more to suit your needs.