Laravel: Difference Between Route Middleware and Policy

前端 未结 3 1607
天命终不由人
天命终不由人 2021-01-30 11:21

Developing an app with laravel I realised that what can be done with Policy can exactly be done with Middleware. Say I want to prevent a user from upda

3条回答
  •  不知归路
    2021-01-30 12:03

    Route middleware allows you to apply request handling to a large range of routes, instead of repeating the code in every controller action - checking authentication and redirecting guests is a good example. Controllers instead contain logic unique to specific routes/actions - you could use middleware for this, but you'd need separate middleware for every route's logic and it would all get very messy.

    Policies/abilities are simply a way of checking user permissions - you can query them from a controller, or from middleware, or anywhere else. They only return true or false, so they aren't equivalent to controllers or middleware. Most of the time abilities will be comparing a user to another model, which will have been loaded based on an identifier sent to a controller action, but there are probably some applications for use with middleware too.

提交回复
热议问题