Learning Laravel: Protected Routes and Authentication

Previously in this series, we have looked at how to install laravel, how laravel works, and how to deploy a laravel app.  In today’s post, we are going to look at how you would protect a route so that the user would need to login in order to view a webpage.

Step #1:  Create a laravel project

Before we do anything else, we need to create a laravel app to add protected routes to.  That is as simple as running composer create-project laravel/laravel time-off-calendar from the terminal, in our example.

Step #2:  Add a database to the project

For the purposes of this example, we are going to be hosting this locally (not deploying it anywhere) and we are going to be using SQLite.  To create an SQLite database, you just need to touch database/database.sqlite.

Next, you need to change .env to have the value of “DB_CONNECTION=sqlite”.

At this point, if you run php artisan migrate:status and recieve the “Migration table not found” error, everything is wired up correctly.

Next, you can run php artisan migrate and populate the database.

Step #3:  Add authentication to the project

If you run composer require laravel/ui and php artisan ui vue --auth, it creates an authentication system.

Next, you need to npm install && npm run dev to install the dependencies and run the app.  After that, you can run npm run build to deal with your “Missing Vite Manifest File” and then php artisan serve to see the end result.

You can now go to http://127.0.0.1:8000/ and find not only a laravel site but also login and register pages.

Step #4:  Create a new view to protect

You can create a new blade by typing touch calendar.blade.php in the resources/views folder.

For this example, we will use this:

Step #5:  Create a new controller for your view

You can create a new blade by typing touch CalendarController.php in the app/Http/Controllers folder.

The controller is going to look like this:

Next, you can open routes/web.php and add the line Route::get('/calendar', [App\Http\Controllers\CalendarController::class, 'index'])->name('calendar');.

At this point, our site looks like this:

So, what protects the route?  The answer is that $this->middleware('auth'); line in CalendarController.php.  If we comment it out, you can get to the page without logging in.

What’s next?  In our next Learning Laravel post, we will take the vue-based calendar that we created back in June and add it to our calendar view.  Until then, if you have any questions, comments, etc, please drop a comment, below.

 

[ Cover photo by Mika Baumeister on Unsplash ]

Leave a Reply

Your email address will not be published.