Laravel: Sync Permissions

Al-MooradiAl-Mooradi
1 min read

Sync permissions from Policies directory, and add missing permissions to the permissions table.

Create new command

php artisan make:command SyncPermissionsCommand

Command code

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Spatie\Permission\Models\Permission;

class SyncPermissionsCommand extends Command
{
    protected $signature = 'permissions:sync';

    protected $description = 'Sync permissions from Policies directory';

    public function handle()
    {
        $policiesPath = app_path('Policies');

        $this->scanAndSyncPermissions($policiesPath);

        $this->info('Permissions synced successfully.');
    }

    private function scanAndSyncPermissions($directory)
    {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        $permissions = [];
        foreach ($iterator as $file) {
            if ($file->isFile() && $file->getExtension() === 'php') {
                $filePath = $file->getPathname();
                $fileContent = file_get_contents($filePath);

                preg_match_all('/(?:can|hasPermission)\([\'"]([^\'"]+)[\'"]/', $fileContent, $matches);

                // $matches[1] will contain the captured permission names
                foreach ($matches[1] as $permission) {
                    $permissions[] = [
                        'name' => $permission,
                        'guard_name' => 'web'
                    ];
                }
            }
        }

        Permission::upsert(
            $permissions,
            uniqueBy: ['name', 'guard_name'],
            update: ['name']
        );
    }
}
0
Subscribe to my newsletter

Read articles from Al-Mooradi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Al-Mooradi
Al-Mooradi