Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jeevan628's avatar

Apply Middleware for certain methods

Hi guys,

I got a bit issue with using middleware in L5.

I have a resource called 'Post' like below

Route::resource( 'post', 'PostController' );

Now I wanna apply middle 'auth' on create,store,edit and delete method and let user access to index, show without logging in.

Not sure how to do that.

Thank you in advance.

0 likes
3 replies
perkola's avatar
perkola
Best Answer
Level 3

You can add middleware for certain routes in the constructor of the controller like this:

/**
 * Enforce middleware.
 */
public function __construct()
{
    $this->middleware('auth', ['only' => ['create', 'store', 'edit', 'delete']]);
    // Alternativly
    $this->middleware('auth', ['except' => ['index', 'show']]);
}
25 likes
jeevan628's avatar

Aha, That works !!!!. Couldn't see this syntax in the documentation.

perkola's avatar

I'm happy to help. Here is the documentation by the way, I agree it could be clearer.

1 like

Please or to participate in this conversation.