Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Authenticating certain controller methods in Laravel

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 (including 8.1, 8.2, 8.3, and 8.4), 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-digest 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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?