Register Form Macros Easily in Laravel 5

profile picture

Register Form Macros Easily in Laravel 5

While working on a new project at work I had to create a custom form input. The goal was to have a select list of the days of the week. If there is already a form method to do so with the Months of the year, there's no default method for the weekdays. So I had to create my custom select list.

And I obviously don't want to put an array of 7 items directly in my view file. Solution ? Form Macros !

These helpers let's you create custom form elements, and call them into your blade views.

Unfortunately there is no good documentation about how registering these macros, and where to write them in your code in order for the snippet to be actually accessible within your views.

According to multiple posts I saw on stackoverflow and on laravel.io, the best way is to register a new Service Provider.

Let's do exactly that :

/app/Providers/FormMacroServiceProvider.php

namespace App\Providers;

use Form;
use Illuminate\Support\ServiceProvider;

class FormMacroServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        Form::macro('selectWeekDay', function () {
            $days = [
                'monday'    => 'Monday',
                'tuesday'   => 'Tuesday',
                'wednesday' => 'Wednesday',
                'thursday'  => 'Thursday',
                'friday'    => 'Friday',
                'saturday'  => 'Saturday',
                'sunday'    => 'Sunday',
            ];
            return Form::select('day', $days, null, ['class' => 'form-control']);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

This example depicts how I created the select list I needed for my project. You can of course define any macros that you want.

If you have a lot of macros to create, and you don't want to put all of them into a single file because it's too messy, then you should include separate files, as suggested into this example.

Finally, don't forget to load your new service provider in the providers array:

/config/app.php

'providers' => [
    // ...
    App\Providers\FormMacroServiceProvider::class,
],

Now in your blade views, you can simply do that:

{!! Form::selectWeekDay() !!}

Wonderful !!

Enjoy your webforms !

2019 My Dynamic Production SPRL All rights Reserved.