Since I was learning next.js, I also start learning laravel API. I generally used laravel with livewire and stuff and never touch API. I started reading the docs and follow the instructions.
I install the API (sanctum) using this command provided by laravel:
php artisan install:api
Then I created a simple login
public function store(Request $request): IlluminateHttpJsonResponse
{
$credentials = $request->validate([
'email' => 'required',
'password' => 'required',
]);
if (Auth::attempt($credentials)) {
return response()->json([
'message' => 'Invalid Credentials',
], 401);
}
return response()->json([
'access_token' => Auth::user()->createToken('auth_token')->plainTextToken,
]);
}
And define my routes
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
use AppHttpControllersAuthenticatedSessionController;
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
Route::post('/login', [AuthenticatedSessionController::class, 'store']);
Now, I started the local server and access the API using postman. I’m expecting a 419 error when I access the login page since I’m not accessing the csrf route. But I get a 404 not found error. Then I tried access the route define by laravel which is user and it return 404 too. So I run php artisan optimize:clear
and still the error persist. Also after installing the api I removed the web routes, so I thought maybe it is required, so define the web routes again and clear the routes but still the error is there. So I tried defining a routes in web and that works. But based on the docs it should start working after we install the api. Is there something I’m missing or doing wrong?