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

pedroroccon's avatar

API and Route Model Binding

Hello everyone!

I'm developing a very simple users API (Create, Read, Update, Delete). I already have my controllers setup and currently I'm using Isomnia to make my requests, but now i'm facing a problem.

In my routes/api.php file I added a "web" middleware, wich implements the CSRF Token. When I try to do a PATCH in Insomnia, the application throwns an execption with message "CSRF token mismatch".

I know that if I remove the "web" middleware i can solve this problem, but if I do that I can't use Route Model Binding.

Here is my routes file

Route::group(['prefix' => 'api', 'middleware' => ['web', 'auth:api']], function () {
    Route::resource('users', 'UserController');
});

Here is my UserController

public function update(UserRequest $request, User $user)
{
    $user->fill($request->except('password'));

    if ( ! empty($request->password)) {
        $user->password = bcrypt($request->password);
    }

    $user->update();

    if ($request->wantsJson()) {
        return $user->toJson();
    }
    
    return redirect($user->path());
}

Note: I'm using the same controller for API and my web application, make sense?

Anyone knows a solutions for that problem? Regards!

0 likes
6 replies
bugsysha's avatar

Your problem is caused by using web and auth:api middleware on same route. Split it into two routes. One prefix with api and other without it.

pedroroccon's avatar

Hello @bugsysha

Yes, I know that. But doing this, my Route Model Binding stops working, wich means that I always need put a User::findOrFail($user) to fetch my model. The Route Model Binding only works if I have the web middleware setted, and I'm using the same controller for web and API.

bugsysha's avatar

What have you changed in Http kernel? Or are you doing something with middleware in Service providers? Or maybe some package you've installed?

pedroroccon's avatar

@bugsysha I didn't change anything... It's just a simple API request, but I want to use the same controller for my frontend and API calls. But unfortaly, when I remove the web middleware, the Route Model Binding forcing me to add a User::findOrFail() on every controller that I want to return the user. Should I separate the Api Controller from my Web controller?

bugsysha's avatar
bugsysha
Best Answer
Level 61

Try to reproduce that bug without changing anything in a fresh Laravel install and you should see that everything is working. That would be such a huge bug that everyone would notice it and it would be fixed very fast.

pedroroccon's avatar

@bugsysha All right! I'll try to replicate that in a new Laravel installation, and then I'll give a feedback here! Thanks! :D

Please or to participate in this conversation.