Laravel Permissions through Gates

Laravel Permissions through Gates

If you are building small application or big enterprise application roles and permissions are vital part of the application. For example if you are building a blog and you have two roles like editor and admin, it is easy to implement it by considering just a variable and checking that variable on login to permit a user to certain action but the problems is as your application will go bigger roles will increase like publisher, user, reviewer etc so it is a good practice to implement it through permissions and Laravel has a very good way if implementing these type of situation in the form of Gates.

Laravel
Laravel Category

If you want to implement roles and permissions from scratch customly then read this article.

If you want to implement roles and permissions through Policies then read this article.

You can read about the Gates here from Laravel official docs.

For example if you are building a blog website and you have a publisher and whatever it is used, you will check if the user having publisher role can publish article or can read articles etc and those permissions in Laravel are called Gates.

In Laravel you define a Gate and Rule and whatever you want to use that Gate you just check if the Gate allows or deny the request and in the blade there are build in directives like @can, @cannot, @canany which means that all the roles will be define in Auth Service provider where you will define all the gates and that gates will be the only place if you want to changes something in the roles.

In the AuthServiceProvider you can define the Gates as

use App\Models\User;
use Illuminate\Support\Facades\Gate;
/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();
    Gate::define('publish-articles', function (User $user) {
        return $user -> is_publisher;
    });
}

You will check in the controller functions like

    public function store(Request $request)
    {
        if (! Gate::allows('publish-articles')) {
            abort(403);
        }
        // store the article...
    }

In the blade views you can allow and disallow by using blade directives as @can etc.
Gates are the most easy way implement roles and permissions and you can read in detail about Gates from Laravel official docs.

Follow us TwitterFacebookLinkedIn

Open Source Listing

Previous Post
Next Post

Comments

Laravel Permissions through Policies - Open Source Listing

[…] through Policies but I you want to implement permissions by gates then must read the article how to implement permissions through gates and if you want to implement your custom roles and permissions you can read the article Custom […]

Leave a Reply