1

I implemented a role/permission system. Now I want to add a method to Laravel router so I can make something like this:

Route::get('sales', 'SaleController@index')->allow('Salesman');

I know that I can use @can('Salesman') (View) and $user->can('Salesman') (Controller) but I found so much readable the way I'm trying to do it since I'll be able to see all role permission access in the routes file.

Alan
  • 2,559
  • 4
  • 32
  • 53

2 Answers2

1

You can override the router class, then register it into service container to be used by Route facade.

To be more clear:

  • Write a class that extends Laravel's router (I think Router class). To find this, open the Route facade, then find its service provider. From there, it should be easy to find the router class.
  • Write a class that overwrites that router. Make sure to extend the class you found before.
  • Write a service provider that overwrites the router services. The practically means to register your service under the same key name you find in Route facade.

And that should be it. Your service is now picked by Route facade automatically.

vfsoraki
  • 2,186
  • 1
  • 20
  • 45
  • 1
    I'm getting this Exception after doing all you said: Declaration of App\Providers\RouteServiceProvider::boot(App\Router $router) should be compatible with Illuminate\Foundation\Support\Providers\RouteServiceProvider::boot(Illuminate\Routing\Router $router) – Alan Jul 21 '16 at 13:39
  • You maybe are extending your provider from Laravel. This is not necessary, and may cause problems like that one. Just read what Laravel does in that provider (`RouteServiceProvider`), and make yours just like that. But replace the `Router` with your own. – vfsoraki Jul 23 '16 at 04:35
  • I'm not extending the provider. I'm extending laravel router. – Alan Jul 23 '16 at 18:31
  • But the error says otherwise, `Declaration of App\Providers\RouteServiceProvider::boot(App\Router $router) should be compatible with Illuminate\Foundation\Support\Providers\RouteServiceProvider::boot(Illuminate\Ro‌​uting\Router $router)` which means `App\Providers\RouteServiceProvider` is extending `Illuminate\Foundation\Support\Providers\RouteServiceProvider` and their `boot` methods' signature are not the same – vfsoraki Jul 24 '16 at 04:58
0

As you're using the facade to generate the routes. This should be quite easy. The facade can be overruled in the config/app.php facades array.

You can generate your own Facade class and replace the native one with yours. Which in fact is a Router class. In order to implement the functionality you need to extend and override the following in sequence:

  • Facade
  • Router::newRoute
  • Route

By extending the last one and returning those in the newRoute method of the Router, you'll be able to overrule the logic of Laravel.

Luceos
  • 6,629
  • 1
  • 35
  • 65