9. Adding Authentication to Routes

In Laravel, it is rather straightforward to implement authentication. My approach involved adding authentication middleware to the appropriate routes that required authentication:

->middleware('auth')

The middleware was only added to routes that required users to be logged in. In my case, guest users are allowed access to the welcome page view (resources/views/welcome.blade.php), accessed at '/'. Guests are also able to access the '/posts' URI, which returns a view showing all of the blog posts (resources/views/posts/index.blade.php). Finally, guest users are able to access the 'posts/{post}' URI, which uses a wildcard - this route returns a view showing a single post (resources/views/posts/show.blade.php).

In addition to the routes accessible by guests, which were implemented by myself, additional views and routes were generated by the application scaffolding. As an example, guest users are able to access URIs such as '/login', which returns a login form view (resources/views/auth/login.blade.php) and '/register' which returns a registration form view (resources/views/auth/register.blade.php).

The routes which I have protected by adding the authentication middleware include those which involve creating, updating and deleting actions. This includes:

  • Showing a view with a create post form
  • Persisting new posts to the database
  • Showing a view with an edit post form
  • Persisting updates to the database
  • Deleting a selected post
The screen capture below shows the routes/web.php file with the authentication middleware in place.


Another approach can be taken when implementing authentication, which can be seen in the home controller (App\Http\Controllers\HomeController.php), added by the application scaffolding. This approach adds authentication within the controller, instead of within the route in the routes/web.php file. The middleware is added within a __construct() function, at the top of the controller file. The screen capture below shows an example of this approach:



Comments