pedroroccon
2 weeks ago
116
6
Laravel

API and Route Model Binding

Posted 2 weeks ago by pedroroccon

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!

Please sign in or create an account to participate in this conversation.