Home > Net >  What causes the "route not defined" error in this Laravel 8 API?
What causes the "route not defined" error in this Laravel 8 API?

Time:04-30

I am working on a registration form with Laravel 8 and Angular 13. The back-end is an API (link to Github repo).

In the UserController I have a signin() and a signout() method:

public function signin(Request $request) {

    $fields = $request->validate([
        'email' => 'required|string',
        'password' => 'required|string'
    ]);

    // Check email
    $user = User::where('email', $fields['email'])->first();

    // Check password
    if(!$user || !Hash::check($fields['password'], $user->password)) {
        return response(['message' => 'Incorrect email and/or password'], 401);
    }

    $token = $user->createToken('secret-token')->plainTextToken;

    $response = [
        'user' => $user,
        'token' => $token
    ];

    return response($response, 201);
}


public function signout(Request $request) {
    auth()->user()->tokens->each(function($token) {
        $token->delete();
    });

    return [
        'message' => 'You have been signed out'
    ];
}

In routes\api.php I have:

Route::post('/signup', [UserController::class, 'signup']);
Route::post('/signin', [UserController::class, 'signin']);

Route::group(['middleware' => ['auth:sanctum']], function () {
  Route::post('/signout', [UserController::class, 'signout']);
});

The problem

When I access https://mysite.test/api/signout, in Postman, I get the error:

Route [login] not defined.

Where is my mistake?

CodePudding user response:

Its hitting the Authenticate Middleware where by default it redirects you to route('login'). This is because when you delete the token the user doesn't have access through auth:sanctum so it redirects the Unauthenticated user to the login route that doesn't exists. Just change the redirect in Middleware/Authenticate to signin/signout route.

Change the singout() in your Controller to this

Auth::guard($this->guard())->logout();

Request::session()->invalidate();

Request::session()->regenerateToken();

This will logout the user without hitting the Authenticate Middleware, it will return a json response of 204 or No Content. NOTE: just change your set guard instead of $this->guard() I recommend adding a private function inside of your UserController so you can get the correct guard every time and that would look like this

if(isset($this->guard) && $this->guard) {
    return $this->guard;
}

return config('auth.defaults.guard');

CodePudding user response:

In headers(postman), add following key value

Accept : application/json

  • Related