Laravel 5 Helpers

Helpers are basically useful functions top-level integrated that you can call wherever inside your application. If they have not been provided with the core, you might ended developing one for yourself.

We manually create our Helper Class file:

app/Helpers/Total.php: our main helpers file. It contains all the Helper’s logic.

namespace App\Helpers;

class Total{

    public static function resume( ){

        return response()->json( [ 'total' => '1.000.000 $']);

    }
}

In this example we return a JSON response.

Then go to the console and create the Service Provider TotalServiceProvider. It loads our Helper class

php artisan make:provider TotalServiceProvider
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class TotalServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        require_once app_path() . '/Helpers/Total.php';
    }
}

We need to make some changes to our config/app.php file. In this file we are going to set our provider of personal services, and it also helps us to set an alias for he Helper so we don’t need to use the absolute name of the Class into the Helper.

Now we need to inform Laravel about our Service Provider, so laravel can load it up when booting. So on config/app.php register the Service Provider.

'providers' => [
    ...

    App\Providers\TotalServiceProvider::class,

    ...

]

To use our Helper properly, we can also create an alias by adding:

'aliases' => [
    ...

    'Total' => App\Helpers\Total::class,

    ...
]

Now, from our controller:

...

use App\Helpers\Total;

...

public void someFunction(){
    $resume = Order::resume();
    return $resume->getData()->total;
}