🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Protecting Routes

An auth guard protects a route from guests. A guest is sent to the login page instead.

A protected route

The auth middleware stands in front of the route.

Route::get('/l44/dashboard', function () {
    return 'Dashboard for '.Auth::user()->name;
})->middleware('auth');

The login route

The login route has a name, so the middleware can find it.

Route::get('/login', function () {
    return 'Login page';
})->name('login');

A second protected route

The same middleware protects any route.

Route::get('/l44/profile', function () {
    return 'Profile of '.Auth::user()->name;
})->middleware('auth');

Example

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::get('/login', function () {
    return 'Login page';
})->name('login');

Route::get('/l44/dashboard', function () {
    return 'Dashboard for '.Auth::user()->name;
})->middleware('auth');

Key points

  • Auth guard: the auth middleware on a route.
  • Use the auth middleware to protect a route.
  • A guest is sent to the login page.
  • A logged in user reaches the route.

In this example, the login route is named login. The dashboard route carries the auth middleware. A logged in user sees the dashboard greeting. A guest is sent to the login page. An auth guard protects a route from guests. Visit /l44/dashboard in the browser to see the output.

Note

A route can protect one page while the rest of the site stays open.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when a guest visits a route with the auth middleware?