Blog Detail

01

Sep
Generate Robust Laravel Authorization Without Writing Code cover image

arrow_back Generate Robust Laravel Authorization Without Writing Code

Laravel Authorization is a fantastic package that helps you to quickly create strong policy authorization logic in your Laravel application with minimal effort. In most cases, the defaults will be just enough and all you’d need to do is authorize.

Installation

You can install the package via composer:

composer require flixtechs-labs/laravel-authorizer

You can publish the config file with:

php artisan vendor:publish --tag="laravel-authorizer-config"

This is the contents of the published config file:

return [
    'permissions' => [
        'create',
        'update',
        'delete',
        'view all',
        'view',
        'force delete',
        'restore',
    ],
];

Setup

This package depends on the spatie/laravel-permission package. It’s installed automatically when you install this package.

To set up the package all you need to do is run the following command:

php artisan authorizer:setup

If your project is ready you can generate the permissions on a setup by adding the –permissions option:

php artisan authorizer:setup --permissions

You can also generate the policies on a setup by adding the --policies option:

php artisan authorizer:setup --policies

Usage

This package generates a batteries included policy skeleton. You just have to generate a policy and authorize it in your controllers.

Generate a policy for one model

php artisan authorizer:policies:generate Post --model=Post

This will generate a PostPolicy in the App\Policies\ namespace.

Now all you just need to do is authorize the user in your controllers:

<?php

namespace App\Controllers;

use App\Models\Post;

public function __construct()
{
    $this->authorizeResource(Post::class, 'post');
}

Or authorize per action

public function update(UpdatePostRequest $request, Post $post)
{
    $this->authorize('update', $post);
}

Generating policies for all models

php artisan authorizer:policies:generate

This will generate policies for all models in your project.

Generating permissions for one model

php artisan authorizer:permissions:generate --model=Post

This will generate all the CRUD permissions for one specific model. You can add additional permission to be generated by adding them to the config file in config/authorizer.php

Or you can just generate for all the models

php artisan authorizer:generate:permissions

For more details, you can visit Github.

Published at : 01-09-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project