Restricting Laravel Controller Access to Authenticated Users

Laravel provides two simple middleware-driven solutions for restricting controller access to authenticated users. In fact every new Laravel project implements one of the solutions by default, restricting access to the Home controller. In this blog entry adapted from our book, "Easy E-Commerce Using Laravel and Stripe", we'll show you how to restrict your own controllers using middleware.

The first approach involves declaring the middleware restriction within your project's routes.php file. For instance, suppose you've created a special page (managed using a controller named Discounts) which contains various product discounts, and you'd like to restrict access to authenticated users. To do so you can attach Laravel's auth middleware to the Discounts controller by opening app/Http/routes.php and defining the route like so:

Route::get('discounts', [
  'middleware' => 'auth', 
  'uses' => 'DiscountsController@index'
]);

After saving the changes, Laravel will only grant access to the Discounts controller's index action (and associated view) to those users who have signed in!

The second approach is equally effective, involving declaring the middleware within the controller constructor. For instance, if you'd like to restrict access to the entire Discounts controller (as opposed to just a specific route as we demonstrated above), open app/Http/Controllers/Auth/AuthController.php and the following method:

public function __construct()
{
    $this->middleware('auth');
}

As you can see, both solutions are so simple, yet so powerful!


Written by W. Jason Gilmore on Jun 04, 2015

What are you waiting for? Start implementing Stripe and Laravel today!

Buy Now for $29.99

European customers: Leanpub will add VAT to the purchase price.

Stay up to date by joining the newsletter

No Spam, Unsubscribe Anytime