https://dev.to/halimdirgantara disclaimer: This article is taken from https://medium.com/@halimdirgantara/generate-automatic-permission-names-from-routes-with-spatie-laravel-permissions-5661d5bbcc4a which has been published in the medium without being modified In Laravel, Laravel-Spatie is a package that is widely used as a tool for managing users, roles and permissions in the database.
We just need to create roles and permissions to synchronize with the user, so we can set what roles can perform a function or what permissions are allowed to perform a function.
Previously if we were going to create a seeder for the permission name like this: //user permission View | Create | Edit | Delete => USER Permission::create([‘name’ => ‘view user’]); Permission::create([‘name’ => ‘create user’]); Permission::create([‘name’ => ‘edit user’]); Permission::create([‘name’ => ‘update user’]); Permission::create([‘name’ => ‘delete user’]); //user permisson View | Create | Edit | Delete => ROLE Permission::create([‘name’ => ‘view role’]); Permission::create([‘name’ => ‘create role’]); Permission::create([‘name’ => ‘edit role’]); Permission::create([‘name’ => ‘update role’]); Permission::create([‘name’ => ‘delete role’]); //user permisson View | Create | Edit | Delete => PERMISSION Permission::create([‘name’ => ‘view permission’]); Permission::create([‘name’ => ‘create permission’]); Permission::create([‘name’ => ‘edit permission’]); Permission::create([‘name’ => ‘update permission’]); Permission::create([‘name’ => ‘delete permission’]); Then we will replace it with a function like this, First, we retrieve data from the route in our application with this command : $routeCollection = Route::getRoutes()->get(); https://res.cloudinary.com/practicaldev/image/fetch/s--KYl6vWmM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y5kn2vzafn85t6i2h1kz.png
The overall code is as follows : $routeCollection = Route::getRoutes()->get(); foreach ($routeCollection as $item) { $name = $item->action; if(!empty($name[‘as’])) { $permission = $name[‘as’]; $permission = trim(strtolower($permission)); $permission = preg_replace(‘/[\s.,-]+/’, ‘ ‘, $permission); Permission::create([ ‘name’ => $permission ]); }}