Step 12 — Add Authentication (Login, Register, Logout)
In this step, we’ll add authentication to your Laravel 12 CRUD app.
This means users will be able to register, log in, and log out, and only logged-in users can create, edit, or delete posts.
Step 1 — Install Laravel UI
By default, Laravel 12 doesn’t come with built-in authentication.
We’ll use the Laravel UI package to easily generate it.
Run these commands in your terminal:
This will automatically create:
-
Login, Register, and Logout pages
-
Authentication routes
-
Auth controllers and views
-
A sample
HomeController
Step 2 — Install frontend dependencies
To include Bootstrap styles and JS for the authentication pages, run:
💡 If you don’t have Node.js installed, you can skip this step —
your app will still function without the Bootstrap styling.
Step 3 — Run migrations
Laravel already includes a migration for the users table.
Run the migration to create it in your database:
Now your database has a A users table to store registered users.
Step 4 — Protect routes (require login)
We only want logged-in users to manage posts.
Open your controller:
app/Http/Controllers/PostController.php
and add this inside the class:
Now, all post-related routes require users to log in before accessing them.
Step 5 — Update routes
Open your routes/web.php file and replace the old routes with the following:
✅ This setup ensures:
-
/register,/login, and/logoutare available for all users. -
/postscan only be accessed by logged-in users. -
After login, users are redirected to the posts list.
Step 6 — Add Login/Logout links in the layout
Open your layout file:
resources/views/layouts/app.blade.php
Add this small navigation bar before the main container:
Step 7 — Test the authentication
Now test your app:
-
Visit
/register→ create a new user account. -
After login, you’ll be redirected to
/home(which redirects to/posts). -
Visit
/posts→ You can now create, edit, or delete posts. -
Logout → try visiting
/postsagain — you’ll be redirected to the login page.
✅ Authentication works perfectly!
✅ Summary
You have successfully added authentication to your Laravel 12 CRUD app!
It now includes:
-
✅ Login
-
✅ Register
-
✅ Logout
-
✅ Protected Routes

