Tired Of Huge And Complex Coding For Permission Handling?

Tired Of Huge And Complex Coding For Permission Handling?

GO FOR LARAVEL-SPATIE!

·

6 min read

Laravel is open-sourced and one of the most popular web frameworks in the world. It is most common amongst web artisans who prefer web development with PHP. Laravel is widely accepted because of its simple and clean code structure. It uses the well-known MVC or Model-View-Controller architecture. It eases coding for developers by sweating on the small things on its own. Letting us focus more on the crucial parts of our projects.

The most common features of Laravel that will make anyone think twice before starting a project with other frameworks are mentioned below,

MVC Architecture Support

  • Laravel is based on the Model-View-Controller architecture which distances the business logic from the presentation layer of a project. This makes the structure of any project simple and easy to understand. Also, error handling becomes easier as we can determine with certainty where our error occurred, in the business logic part or the presentation part.

Security

  • Laravel is well appreciated for the security it provides to our web application. Common security measurements are taken care of by Laravel instantly when we start creating our project. It intercepts all the requests and processes working like an intermediary system which prevents unethical code injection or hacking. Its built-in CSRF token is quite optimized and handles all kinds of security issues that we may face while data handling.

Template Engine

  • Laravel has its own simple, lightweight but powerful templating engine which is called Blade. The most impressive thing about Blade is its power to give us the ability to use plain PHP codes in our template. This makes our website more dynamic. And using plain PHP on our template ensures us clear readability and understanding of our coding environment.

Artisan CLI

  • Laravel offers a built-in command-line tool called Artisan. Artisan makes our coding journey a treat for us. It helps us automate the tiresome repetitive tasks that are required for our project like creating Controller files for implementing our business logic. Also, it is possible for us to easily manage our database system such as creating models, model migrations with Artisan CLI.

Libraries and Modules

  • One of the main key features of Laravel is its huge collection of Object-Oriented libraries. It also provides us with pre-installed libraries when we start our project which is a rare thing working with other PHP web frameworks. The most common libraries and packages of Laravel are Breeze(A starter kit for authentication purposes), Socialite(For authentication via social platforms e.g. Facebook, Google, etc), Cashier(For managing subscriptions and packages), Vapor(For a serverless deployment platform), and many more.

Spatie- A Laravel Library Package For Permission Handling

User management is the most common thing in any website. If you are building a project it is certainly built for some kind of user. Complex projects have more than one user group. So to separate a user group from others we assign Roles to them and give specific Permissions to specific roles so that we can easily handle what a particular user group can do or view on our website. Maintaining roles and permissions in a smaller project may not be required or easy to handle but in any large and complex project it gets pretty tough or the queries are likely to lose efficiency.

As Laravel is there to make our coding journey a ride to Disney Land, it offers us a very useful package that handles all Roles and their Permissions for us. This package is called Spatie.

Spatie is a library package offered by Laravel that manages all user roles and user permissions in the database for us. It is quite easy to install in our project and start working with. The basic structure and functionalities of Spatie are undoubtedly easy to understand. Let us discuss the installation method and basic usages of Spatie in the following passages,

Installation

Spatie can be installed via composer by the command,

composer require spatie/laravel-permission

This will publish a "config/permission.php" file. We now have to configure the service provider of our "config/app.php" file by the following,

'providers' => [

    \\...
    Spatie\Permission\PermissionServiceProvider::class,

];

Now to publish the migration and the "config/permission.php" file,


php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

After that, we have to clear our config cache by using,


php artisan optimize:clear

or


php artisan config:clear

Finally, we have to run our migrate command for necessary migrations needed for our database,


php artisan migrate

Lastly, Spatie offers us middlewares like RoleMiddleware, PermissionMiddleware, and RoleOrPermissionMiddleware. We can add them inside our "app/Http/Kernel.php" file to use these middlewares. This can help us protect our routes.


protected $routeMiddleware = [

    // ...
    'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
    'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
    'role_or_permission'=>
                  \Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::class,

];

Thus installing the Spatie package in our Laravel Web Project is done. Now we are ready to assign roles and give permission to our users. Let us see the basic usage that will help us better understand how to use Spatie functions.

Basic Usage

Before starting to use Spatie commands we have to add some necessary lines to our User model,


use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // ...
}

Spatie helps developers assign a user to a role and give that role one or multiple permissions. A Role and Permission are regular eloquent models that require a name that can be created by the following commands,


use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

$role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);

A permission can be assigned to a role by one of the following lines,


$role->givePermissionTo($permission);

or


$permission->assignRole($role);

To give multiple permissions to a role we can use either,


$role->syncPermissions($permissions);

or


$permission->syncRoles($roles);

Assigned permission can also be revoked by one of the following commands,

$role->revokePermissionTo($permission);

or


$permission->removeRole($role);

As we said earlier Role and Permission models are basically Eloquent models, we are able to perform basic eloquent calls as well,


$all_users_with_all_their_roles = User::with('roles')->get();
$all_users_with_all_direct_permissions = User::with('permissions')->get();
$all_roles_in_database = Role::all()->pluck('name');
$users_without_any_roles = User::doesntHave('roles')->get();
$all_roles_except_a_and_b = Role::whereNotIn('name', ['role A', 'role B'])->get();

For an in-depth analysis of the usage of Spatie please visit Laravel-Permission

In Conclusion

Spatie is here to help us smoothen our coding experience. Now we can easily create a role and assign permissions to that role so that our web application can maintain its security and ensure valid functions are being used by valid users. Also as we are able to perform basic eloquent calls to the Role and Permission model generated by the Spatie package we can easily fetch roles and permissions data from our database.

All this is possible because of Laravel. Laravel framework is here to save us from the complexity a developer faces when building an application. In fact, we are so comfortable and satisfied with the Laravel framework that we built an Inventory System with POS named Stocky

Stocky is the ultimate inventory management system built with Laravel working as an API and Pure Vue.js serving the client-side. It is quite easy to install and if you are thinking to run your business efficiently Stocky is here to save your day.

For more details please visit Stocky

If you are interested in Laravel and thinking of building your website's admin dashboard working with Laravel, do consider Aatrox as your new admin panel dashboard.

Aatrox is also built with Laravel and we used Tailwind CSS for the design so that you can easily install Aatrox and customize it in any way you want. It has a lot of awesome features, packages, and widgets that you can work with.

For more details please visit Aatrox