Search code examples
laravelauthenticationlaravel-authenticationlaravel-9laravel-api

Laravel 9 authentication without package showing error


I've created a login route and it is working ok , but when trying to store data of authenticated users it is showing an error that GET method is not supported but I'm using POST method. But it is getting the below URL as GET method.

"http://127.0.0.1:8000/api/login"

The GET method is not supported for this route. Supported methods: POST.

My Login route

Route::post('/login',[UserController::class,'login'])->name('login');

Response after login

 {
 "person": {
 "_token": "WBHtlTsFtJOSdWx28nHMbtbQyUBB1vkSTjkhpb8t",
 "first_name": "Navid",
 "last_name": "Anjum",
 "email": "[email protected]",
 "password": "11111111"
        }
}

Route to insert data

   Route::post('page/create',[PageController::class,'store'])
->middleware('auth:api')->name('page.create');

Solution

  • I've used Laravel sanctum to fix it.

    Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::post('page/create',[PageController::class,'store'])->name('page.create');
    Route::post('page/post',[PostController::class,'store'])->name('post.create');
    Route::post('/page/{pageId}/attach-post',[PostController::class,'from_page'])->name('page.post');});
    

    In httm->kernel sanctum was commented out.So that's why It did not work previously when I tried with it.

     'api' => [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],