Skip to content

Commit c7e5c76

Browse files
authored
allow can method to be chained onto route for quick authorization middleware additions (#39464)
1 parent bc50a9b commit c7e5c76

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/Illuminate/Routing/Route.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1040,6 +1040,20 @@ public function middleware($middleware = null)
10401040
return $this;
10411041
}
10421042

1043+
/**
1044+
* Specify that the "Authorize" / "can" middleware should be applied to the route with the given options.
1045+
*
1046+
* @param string $ability
1047+
* @param array|string $models
1048+
* @return $this
1049+
*/
1050+
public function can($ability, $models = [])
1051+
{
1052+
return empty($models)
1053+
? $this->middleware(['can:'.$ability])
1054+
: $this->middleware(['can:'.$ability.','.implode(',', Arr::wrap($models))]);
1055+
}
1056+
10431057
/**
10441058
* Get the middleware for the route's controller.
10451059
*

tests/Routing/RoutingRouteTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1926,6 +1926,24 @@ public function testRoutePermanentRedirect()
19261926
$this->assertEquals(301, $response->getStatusCode());
19271927
}
19281928

1929+
public function testRouteCanMiddlewareCanBeAssigned()
1930+
{
1931+
$route = new Route(['GET'], '/', []);
1932+
$route->middleware(['foo'])->can('create', Route::class);
1933+
1934+
$this->assertEquals([
1935+
'foo',
1936+
'can:create,Illuminate\Routing\Route',
1937+
], $route->middleware());
1938+
1939+
$route = new Route(['GET'], '/', []);
1940+
$route->can('create');
1941+
1942+
$this->assertEquals([
1943+
'can:create',
1944+
], $route->middleware());
1945+
}
1946+
19291947
protected function getRouter()
19301948
{
19311949
$container = new Container;

0 commit comments

Comments
 (0)