Creating Laravel Helpers

Published by at 9th January 2018 5:26 pm

Although helpers are an important part of Laravel, the documentation doesn't really touch on creating them. Fortunately, doing so it fairly easy.

Here I'm building a helper for formatting dates for the HTML5 datetime-local form input. First we define the helper function in app\Helpers.php:

1<?php
2
3use Carbon\Carbon;
4
5if (!function_exists('format_date')) {
6 function format_date(string $date)
7 {
8 return Carbon::parse($date, config('app.timezone'))->format('Y-m-d\TH:i:s');
9 }
10}

Then we create a service provider to load them:

1<?php
2
3namespace App\Providers;
4
5use Illuminate\Support\ServiceProvider;
6
7class HelperServiceProvider extends ServiceProvider
8{
9 /**
10 * Bootstrap the application services.
11 *
12 * @return void
13 */
14 public function boot()
15 {
16 //
17 }
18
19 /**
20 * Register the application services.
21 *
22 * @return void
23 */
24 public function register()
25 {
26 //
27 require_once app_path() . '/Helpers.php';
28 }
29}

Finally,we register the service provider in config/app.php:

1 'providers' => [
2
3 ...
4 App\Providers\HelperServiceProvider::class,
5 ],

Of course, once you have this all set up for one helper, it's easy to add more because they can all go in app/Helpers.php.

Creating your own helpers is a good way of refactoring unwanted logic out of your Blade templates or controllers and making it more reusable and maintainable, particularly for things like formatting dates or strings.