Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

samshervarma's avatar

How to Load Form Macros in Laravel 5

I am beginners in laravel 5 . Please help any one. How to create macros function and where are put. please give small example.

0 likes
6 replies
sitesense's avatar

@samshervarma

In your composer.json make sure you include illuminate/html.

"require": {
    "laravel/framework": "5.0.*",
    "illuminate/html" : "5.*",

Run composer update.

In app/config/app.php

// add this to the providers array
'Illuminate\Html\HtmlServiceProvider',
'App\Providers\MacroServiceProvider',

// add this to the aliases array
'Form'      => 'Illuminate\Html\FormFacade',
'HTML'      => 'Illuminate\Html\HtmlFacade',

Create like this:

app/Services/Macros.php

<?php namespace App\Services;

use Illuminate\Html\FormBuilder;

/**
 * Class Macros
 * @package App\Http
 */
class Macros extends FormBuilder {

    /**
     * @param $name
     * @param null $selected
     * @param array $options
     * @return string
     */
    public function selectState($name, $selected = null, $options = array())
    {
        $list = [
            '' => 'Select One...',
            'AL' => 'Alabama',
            'AK' => 'Alaska',
            'AZ' => 'Arizona'
        ];

        return $this->select($name, $list, $selected, $options);
    }
}

EDIT: Add a service Provider:

app/Providers/MacroServiceProvider.php

<?php namespace App\Providers;

use App\Services\Macros;

/**
 * Class MacroServiceProvider
 * @package App\Providers
 */
class MacroServiceProvider extends \Illuminate\Html\HtmlServiceProvider {

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

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        parent::register();

        $this->app->bindShared('form', function($app)
        {
            $form = new Macros($app['html'], $app['url'], $app['session.store']->getToken());
            return $form->setSessionStore($app['session.store']);
        });
    }
}

Then include in a view like this:

{!! Form::selectState('state', 'AK', ['class' => 'form-control']) !!}

I think that should set you on your way :)

1 like
Jeffberry's avatar

You didn't give him the source to your MacrosServiceProvider, with your current instructions your Macro class would not be used anywhere in the system.

kupcza's avatar

@bestmomo hi, I tried LaravelCollective with macros, but after creating App/macros.php and loaded it using composer, I still cannot use Form::macro();

(that's not class, just basic php file like e.g. helpers.php)

Maybe it's just too late and I'm tired, but have this err: Fatal error: Class 'Form' not found in ....macros.php

Please or to participate in this conversation.