Skip to content

Chapter 5 of 7

Authentication, Authorization, and Sessions

Laravel provides two complementary authorization layers: gates (closures) and policies (classes). Define gates in AuthServiceProvider with Gate::define('update-post', function (User $user, Post $post) { return $user->id === $post->user_id; }), then check with Gate::allows('update-post', $post) or @can('update-post', $post) in Blade. Policies organize authorization logic around a specific model: generate with make:policy PostPolicy --model=Post, and methods like update(User $user, Post $post) map directly to abilities. Inside controllers, $this->authorize('update', $post) throws an AuthorizationException (403) when denied, or you can use $user->can('update', $post) for a boolean check. Gates are best for simple, general checks; policies win for any non-trivial model.

Reading the current user is straightforward: auth()->user() or Auth::user(). Log a user in programmatically with Auth::login($user), Auth::loginUsingId(5), or Auth::attempt(['email' => $email, 'password' => $pw], $remember = true); the last one verifies credentials against the configured guard and starts a session. Passing true as the second argument issues a long-lived remember-me cookie that authenticates the user on subsequent visits even after the session expires. Check Auth::viaRemember() to detect this case in your application logic. For API token issuance with cookies for SPAs and bearer tokens for mobile apps, use Sanctum: $user->createToken('app')->plainTextToken returns a token clients send as a bearer credential, while SPAs authenticate via the shared laravel_session cookie once configured in config/sanctum.php.

Sessions back all of this state. Store values with session(['key' => 'value']), retrieve with session('key', 'default'), and use flash() for data that should survive exactly one redirect, such as status messages: $request->session()->flash('status', 'Saved!'). now() is the request-scoped variant that does not persist across the redirect; keep() re-flashes for an additional request. After login or privilege escalation, call $request->session()->regenerate() to write a new session ID and migrate data, preventing session fixation attacks; pair with ->invalidate() on logout to drop all session data. Session drivers (file, cookie, database, redis, array) are configured in config/session.php.

All chapters
  1. 1The HTTP Layer: Routing and Middleware
  2. 2Eloquent ORM: Models, Relationships, and Querying
  3. 3Database Migrations, Schema, and Data Seeding
  4. 4Blade Templates, Views, and Pagination
  5. 5Authentication, Authorization, and Sessions
  6. 6Queues, Events, Notifications, and Broadcasting
  7. 7Service Container, Facades, and Cross-Cutting Concerns

Drill it

Reading is not remembering. These come from the Laravel Framework deck:

Q

What is Laravel Eloquent ORM?

Eloquent is Laravel's built-in Active Record ORM. Each database table has a corresponding Model class used to interact with that table. It provides an expressiv...

Q

How do you define a one-to-many relationship in Eloquent?

In the parent model, define a method returning hasMany():public function posts() { return $this->hasMany(Post::class); }In the child model, define the inverse w...

Q

What is eager loading in Eloquent and why is it important?

Eager loading solves the N+1 query problem by loading relationships upfront:$books = Book::with('author')->get();Without it, accessing a relationship in a loop...

Q

How do you create a new Eloquent model and migration together?

Use the Artisan command:php artisan make:model Post -mThe -m flag generates a migration file alongside the model. You can also add -f for a factory and -s for a...