Laravel for Beginners: Setting Up Your First Project
A complete first-day guide to Laravel — installation, folder structure, your first route, and your first migration.
Laravel Sanctum is the right choice when a JavaScript frontend (Vue, React, Next.js) or a mobile app needs to authenticate against your Laravel API — it's far lighter than a full OAuth2 server like Passport, and covers 90% of real-world API auth needs.
Sanctum actually solves two different problems. For a first-party SPA served from the same top-level domain, it uses Laravel's normal session cookies — no tokens involved at all. For mobile apps or third-party clients, it issues API tokens instead. This guide covers the token flow, since that's what most Next.js/React frontends on a separate domain need.
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Then add the trait to your User model:
class User extends Authenticatable
{
use HasApiTokens;
}
Route::post('/login', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
return response()->json(['message' => 'Invalid credentials'], 422);
}
return response()->json([
'token' => $user->createToken('api-token')->plainTextToken,
]);
});
The client stores this token (typically in memory or a secure cookie, never plain localStorage if you can avoid it) and sends it on every request:
Authorization: Bearer {token}
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', fn (Request $r) => $r->user());
Route::apiResource('posts', PostController::class);
});
Route::post('/logout', function (Request $request) {
$request->user()->currentAccessToken()->delete();
return response()->noContent();
})->middleware('auth:sanctum');
Sanctum tokens can carry specific abilities, so a token issued to a read-only integration can't accidentally delete data:
$user->createToken('mobile-app', ['posts:read', 'posts:write']);
Check them with $request->user()->tokenCan('posts:write') inside a controller before allowing a mutating action.
That's a complete, production-reasonable token auth flow — no third-party auth server required.
A complete first-day guide to Laravel — installation, folder structure, your first route, and your first migration.
API routes, resources, Form Request validation, correct status codes, and Sanctum auth — a real, production-reasonable Laravel API.
One-to-many, many-to-many, polymorphic, and the N+1 query trap that catches almost every Laravel developer at least once.