Skip to content
Vladimir Schneider edited this page Oct 26, 2015 · 2 revisions

This handy new generator allows you to, with a single command, generate the necessary HTML for a form, based on attributes from a provided model. Perhaps an example is in order:

php artisan generate:form tweet

Assuming that I do have a Tweet model and its associated tweet table, this command will output:

{{ Form::open(array('route' => 'tweets.store')) }}
    <ul>
        <li>
            {{ Form::label('author', 'Author:') }}
            {{ Form::text('author') }}
        </li>

        <li>
            {{ Form::label('body', 'Body:') }}
            {{ Form::textarea('body') }}
        </li>

        <li>
            {{ Form::submit() }}
        </li>
    </ul>
{{ Form::close() }}

Pretty neat, huh? It read the attributes and data types, and prepared the markup for you! One less thing to worry about!

Specifying the Form's Method

But what if you intend to update a resource, rather than create a new one? Well, in that case, use the --method option.

php artisan generate:form tweet --method="update"

This will mostly generate the same HTML, however, the Form::open() method will be adjusted, as needed:

{{ Form::open(array('method' => 'PATCH', 'route' => 'tweets.update')) }}

The method option will accept any number of values (add, edit, update, post, create, etc.), but, essentially, you're just telling it whether you are creating or editing a resource. As such, there's only two possible outputs: POST and PATCH (the former being the default).

Custom HTML

What if you don't like the idea of using an unordered list for a form? Use the --html option, along with the name of the element that you'd prefer to use:

php artisan generate:form tweet --html="div"

Now, the generator we'll present the elements within divs!

{{ Form::open(array('route' => 'tweets.store')) }}
    <div>
        {{ Form::label('author', 'Author:') }}
        {{ Form::text('author') }}
    </div>

    <div>
        {{ Form::label('body', 'Body:') }}
        {{ Form::textarea('body') }}
    </div>

    <div>
        {{ Form::submit() }}
    </div>
{{ Form::close() }}

Copying and Saving

At least for now, and unlike the other generators in this package, this command will output the form, at which point you can copy and paste it where needed. Of course, you can always pipe the output to the clipboard or save to a file, using existing tools. For instance:

# copy the output to the clipboard
php artisan generate:form tweet | pbcopy

# save it to a form partial
php artisan generate:form tweet > app/views/posts/form.blade.php