WHY'S YOUR LARAVEL PACKAGE MODEL ROUTE NOT BINDING?

August 8th, 2019 by Kevin Pimentel

If you are like me, you understand the power of writing Laravel packages. I recently found myself writing a Laravel package for a blogging codebase that I am building. I tried to run a test on the update method and found a problem where my model route bindings had stopped, well, binding. They have one job!


I was trying to run a test to hit my update route, like this:

public function test_that_user_can_update_menu()
{
    $this->withoutExceptionHandling();

    $user = $this->signIn();
    $menu = factory(Menu::class)->create();

    $this->get("/menu/{$menu->id}/edit")
         ->assertStatus(200);

    $this->put(route('menu.update', $menu->id), $attributes = [
        'name' => 'Changed'
    ])->assertRedirect('/menu');

    $this->assertDatabaseHas('menus', $attributes);
}


In my MenuController I wasn't doing anything special on the update method.

public function update(MenuRequest $request, Menu $menu)
{
    if ($menu->update($request->validated())) {
        return redirect('/menu');
    }

    abort(403);
}

So why wasn't it working?


The problem stems from the fact that Laravel applies the web middleware to the routes/web.php file. I guess I've become so used to using it, that I forgot all about it. In the Laravel documentation it reads:


The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection.


Laravel has spoiled us all to not have to write SQL or read apparently. After I noticed this I quickly realized what I needed to do. I needed to group my routes and apply the web middleware to them.

Route::group(['middleware' => ['web']], function () {
    Route::resource('/menu', 'Package\Menu\Controllers\MenuController')->middleware('auth');
});


That's all it is!


Kevin Pimentel

There are two types of people in the world: those that code, and those that don’t. I said that! Quote me. My name is Kevin and I’m one of the ones that codes.