Passing a parameter into Laravel Form::open

  • August 26, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

The LaravelCollective form package is as indispensable to me as Laravel itself. I use it to create every single form found within a Laravel project, no matter how simple or complicated that form may be. One common point of confusion among LaravelCollective newcomers is how to pass an ID into the form route. Read on to learn how.

When using resourceful controllers, Laravel will automatically create all of the necessary routes for you. However you'll still need to ensure those URLs are properly crafted so Laravel knows where the request should be handled. Consider the following route definition:

Route::resource('lists','ListsController');

With this route definition in place, Laravel will execute the ListsController's edit action when the URI lists/{id}/edit is requested ({id} being a placeholder for the ID associated with the list you'd like to edit). The form found in the corresponding edit.blade.php file will use the LaravelCollective HTML package's Form::model method, passing in the $list object (which will cause the related form fields to be auto-populated). Additionally, you'll need to pass the list ID into the route like so:

{!! Form::model(
    $list, 
    [
      'route' => ['lists.update', $list->id], 
      'method' => 'put', 
      'class' => 'form'
    ]) 
!!}

When the form is submitted, the ListsController's update action will be executed. If you used Artisan's make:controller generator when creating the resourceful controller, the update method will automatically expect that list ID to be passed along, as the default method signature looks like this:

public function update(Request $request, $id)
{

}

Of course, the first thing you'll typically do in the update method is retrieve the list record:

$list = List::findOrFail($id);

After doing so, you can update the attributes (passed in via the $request object), and save the updated record back to the database!