pickab00's avatar

Difference between Gates and Middleware

So Ive read this article about gates/policies

https://www.google.com/amp/s/appdividend.com/amp/2017/12/13/laravel-gates-tutorial-example-scratch/

And My question was, whats the difference between writing a middleware and gates. In this scenario, I could have used a middleware to block the user from accessing route correct? Can someone please show me other cases used for gates instead of middleware?

0 likes
3 replies
bobbybouwmann's avatar

Well gates and middlewares are complete different things!

MIddlewares can be used to alter the request and response and also for checking things before you get into the controller. That's what we call a before middleware. So that is basically what you're talking about. Denying the user to access to the application.

Documentation: https://laravel.com/docs/5.8/middleware#defining-middleware

However gates are for authorization/permissions. So this basically means you can define if a user can perform a certain action or not. However they don't prevent the user from accessing your application. You have to do that yourself.

Documentation: https://laravel.com/docs/5.8/authorization#gates

In general you can combine the two. So you would use the gate in the middleware to check if the user can access the page or not. Based on that you then allow or deny access. So there is a huge difference between them, but they can work together.

8 likes
pickab00's avatar

Both answers were great. Confusion resolved. Thanks guys. Should have done more research before posting

Please or to participate in this conversation.