First!
php artisan install:api
In bootstrap/app.php:
->withMiddleware(function (Middleware $middleware) {
$middleware->statefulApi();
Now you can just do from within SPA
const response = await axios.post(url, {}, {});
External API:
- Make token on any user
- Pass the token as ‘Authorization’
Route::get('/getToken', function () {
// find admin user
$user = \App\Models\User::find(1);
$token = $user->createToken('myapptoken')->plainTextToken;
ray($token);
});
Route::post('/secret', function (Request $request) {
$data = ['alfa' => 'top_Secret'];
return response()->json($data);
})->middleware('auth:sanctum');
Now, from client:
const response = await axios.post(url, {}, {
headers: {
'Authorization': `Bearer ${token}`,
}
});