Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Authenticating certain controller methods in Laravel

January 22, 2020 ·

There are basically two ways of using the auth middleware to authenticate the routes in Laravel.

You would either…

  • Attach the auth middleware to the route itself like so.
Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth');

Or

  • If you are using controllers, you may call the middleware method from the controller’s constructor instead of attaching it in the route definition directly like so.
public function __construct()
{
    $this->middleware('auth');
}

Here, in the above approach, the auth middleware will get applied to each of the controller methods. What if you want to apply the middleware only on certain methods? Laravel has a provision for this as well.

Using except and only options

By providing except and only options to the middleware method as a second argument, it’s possible to choose which controller’s methods will get bound by the authentication.

Here’s how you can use the only option,

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

As you can see here, you can provide an array containing all the methods that you would want to get authenticated. Rest of the methods will work without being authenticated.

Similarly, here’s how you can use except option,

public function __construct()
{
    $this->middleware('auth', ['except' => ['index', 'show']]);
}

Here, you can provide an array containing all the methods that you would not want to get authenticated. Rest of the methods will get authenticated as usual.

Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?