Using Laravel Middleware With a Specific Action

  • March 10, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Laravel 5's middleware feature is great for removing redundant logic from your actions. This convenience is particularly evident when you want to restrict certain controllers to authenticated users. But what if you wanted to restrict access to specific actions found within a controller? Read on to learn how.

To restrict access to an entire controller you can reference Laravel's built-in auth middleware in the constructor like so:

class LinkController extends Controller {

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

    ...

}

Once in place, any request sent to any Link controller action will first be passed through the auth middleware, which will determine whether a session is active. If not, the request will be redirected to the login page.

However, what if you wanted to restrict access to a specific controller action, while allowing guests to visit other actions? This is a common problem when you want to provide read access (via index and show) to a particular resource, but restrict resource creation, modification, and/or destruction to authenticated users. Fortunately this is easily accomplished with a minor change to the above example. Suppose you wanted to restrict access to a resourceful controller's create and store actions. You can do so as follows:

class LinkController extends Controller {

    public function __construct() {
      $this->middleware('auth', ['only' => ['create', 'store']]);
    }

    ...

}