Creating Laravel Helpers
Published by Matthew Daly 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<?php23use Carbon\Carbon;45if (!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<?php23namespace App\Providers;45use Illuminate\Support\ServiceProvider;67class HelperServiceProvider extends ServiceProvider8{9 /**10 * Bootstrap the application services.11 *12 * @return void13 */14 public function boot()15 {16 //17 }1819 /**20 * Register the application services.21 *22 * @return void23 */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' => [23 ...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.