Laravel is an extremely fun PHP framework that offers many convenient tools.

For most web applications, a person using Laravel will usually build the basic CRUD functionality for various resources. We've written about the CRUD part of Laravel before.

In this quick tip, we'll be talking Laravel Form Model Binding, which helps the UPDATE portion of our applications.

What is Form Model Binding?

Normally, when we create an edit form, you would pull in the data of the item you want to edit. Then you would use that to populate your form's input fields.

With Form Model Binding, your edit forms are automatically populated based on the item you send to the view using Laravel.

Let's Demonstrate

First, we need to send data to our edit form. To do that, let's set up our route. Since this is just a demonstration, we'll just say we have an imaginary model already set up called Nerd.

Our Nerd will have 3 fields in our database.

  • id
  • name
  • email

Form Route

// routes.php

    // route to show our edit form
    Route::get('nerd/edit/{id}', array('as' => 'nerd.edit', function($id) 
        // return our view and Nerd information
        return View::make('nerd-edit') // pulls app/views/nerd-edit.blade.php
            ->with('nerd', Nerd::find($id));

    // route to process the form
    Route::post('nerd/edit', function() {
        // process our form

Now we have our route to show our Nerd. There are many different ways you could set up this route. You can use resource controllers or just create the route yourself (like we did above).

That's it for our route. Now that we have sent our Nerd to our edit view, let's go look at how Form Model Binding works.

Form Edit View

Normally, to create a form using Laravel, you would use echo Form::open() or if you are using the Laravel Blade templating engine, you would use {{ Form::open() }}.

When using Form Model Binding, you just have to make one very small adjustment: use {{ Form::model() }}. With that one adjustment, our form will automatically be populated!

<!-- app/views/nerd-edit.blade.php -->

    {{ Form::model($nerd, array('route' => 'nerd.edit', $nerd->id)) }}    

        <!-- name -->
        {{ Form::label('name', 'Name') }}
        {{ Form::text('name') }}

        <!-- email -->
        {{ Form::label('email', 'Email') }}
        {{ Form::email('email') }}      

        {{ Form::submit('Update Nerd!') }}

    {{ Form::close() }}

Clean and Simple

Laravel brings in great features and this is definitely one of them. Just like that, you are able to bind data from a model to a form and populate the form easily.

If you have any further questions, take a look at the Laravel Docs on Form Model Binding.

Chris Sevilleja

Co-founder of Slapping the keyboard until something good happens.