DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

User Roles and Permissions Using Centralized Database in Laravel 10

Hey there! Welcome to my article on managing user roles and permissions using a centralized database in Laravel 10. If you're like me, you've probably worked on projects where managing user access levels can quickly become a headache.

Whether granting specific permissions to certain users or defining different roles within your application, it can get complicated fast. Thankfully, Laravel provides us with powerful tools to streamline this process. With the advent of Laravel 10.

In this article, I'll guide you through implementing user roles and permissions in Laravel 10 using a centralized database approach.

So, let's see user roles and permissions using a centralized database in laravel 10, laravel 10 user roles and permissions, roles and permissions in laravel 8/9/10, and custom roles and permissions in laravel 10.

Step 1: Setup Laravel 10 Project

Begin by creating a new Laravel 10 project using Composer:

composer create-project laravel/laravel user-role-permissions
Enter fullscreen mode Exit fullscreen mode

Step 2: Setup Database

Now, we'll setup the database configuration in the .env file.

DB_CONNECTION_CENTRAL_DB=mysql
DB_HOST_CENTRAL_DB=127.0.0.1
DB_PORT_CENTRAL_DB=3306
DB_DATABASE_CENTRAL_DB=roles_and_permissions_laravel10
DB_USERNAME_CENTRAL_DB=root
DB_PASSWORD_CENTRAL_DB= 
Enter fullscreen mode Exit fullscreen mode

Run migrations to create these tables:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 3: Create Roles and Permissions Tables

Then, create a roles and permissions table using the following command.

php artisan make:migration create_roles_table
php artisan make:migration create_permissions_table
Enter fullscreen mode Exit fullscreen mode

Step 4: Create Models

After that, create a model for roles and permissions.

php artisan make:model Role
php artisan make:model Permission
Enter fullscreen mode Exit fullscreen mode

App/Models/Role

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Role as SpatieRole;

class Role extends SpatieRole
{
    protected $connection = 'mysql';
}   
Enter fullscreen mode Exit fullscreen mode

App/Models/Permission

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Permission as SpatiePermission;

class Permission extends SpatiePermission
{
    protected $connection = 'mysql';
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Set Environment

Now, we'll add a set environment for mysql_central_db.

config/database.php

use Illuminate\Support\Str;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

        'mysql_central_db' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL_CENTRAL_DB'),
            'host' => env('DB_HOST_CENTRAL_DB', '127.0.0.1'),
            'port' => env('DB_PORT_CENTRAL_DB', '3306'),
            'database' => env('DB_DATABASE_CENTRAL_DB', 'forge'),
            'username' => env('DB_USERNAME_CENTRAL_DB', 'forge'),
            'password' => env('DB_PASSWORD_CENTRAL_DB', ''),
            'unix_socket' => env('DB_SOCKET_CENTRAL_DB', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => false,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'search_path' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            // 'encrypt' => env('DB_ENCRYPT', 'yes'),
            // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '1'),
        ],

    ],

];
Enter fullscreen mode Exit fullscreen mode

Step 6: Attach Roles and Permissions

In this step, we'll attach roles and permissions in the config/permission.php file.

'role' => App\Models\Role::class,
'permission' => App\Models\Permission::class,   
Enter fullscreen mode Exit fullscreen mode

Step 7: Used Centralized Database

In this step, we'll use a centralized database with the help of env('DB_DATABASE_CENTRAL_DB').

$customerRevenueCharges = DB::table('loads')
    ->select('users.company_name as customer_name',DB::raw("SUM(loads.commission_amount) as total_amount"))
    ->join(env('DB_DATABASE_CENTRAL_DB').'.users',env('DB_DATABASE_CENTRAL_DB').'.users.id','loads.user_id')
    ->orderBy('total_amount','DESC')
    ->groupBy('loads.user_id')
    ->take(10)
    ->cursor();
Enter fullscreen mode Exit fullscreen mode

You might also like:

Read Also: How to Add Dependent Validation using jQuery Validate.js

Read Also: User Roles And Permissions Without Package Laravel 9

Top comments (0)