Permission securing backend

Step 01: Registering all permissions to Gate with AppServiceProvider.php from database table permission_role and role_user

// at the top 
namespace App\Providers; 

use Illuminate\Support\ServiceProvider;
use App\Models\Permission;
use Illuminate\Support\Facades\Gate;
use Illuminate\Database\QueryException;
use Illuminate\Database\Eloquent\Builder;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        try{
            foreach (Permission::pluck('name') as $permission) {
                Gate::define($permission, function ($user) use ($permission) {
                    return $user->roles()->whereHas('permissions', function (Builder $q) use ($permission) {
                        $q->where('name', $permission);
                    })->exists();
                });
            }   
        } catch (QueryException $e) {
        }     
    }
}

Step 02: Adding authorize() methods inside IssueController.php to check permissions for particular roles upon which method access will be authorized or unauthorized 

 public function store(StoreIssueRequest $request) {
    Gate::authorize('issues.create');
    .....
 }
 
 public function show(Issue $issue) {
    Gate::authorize('issues.update');
.... } public function update(Issue $issue, StoreIssueRequest $request) { Gate::authorize('issues.update');
... } public function destroy(Issue $issue) { Gate::authorize('issues.delete');
... }

Code above will go through for roles who have access and if not will return 403 unauthorized who does not have access.

Related Posts


Seeding users and role_user data

Seeding clients and issues data

Adding client column in table

Storing issue in db table

Update issue

Showing user data and logout

Permission securing frontend