PHP code example of daijulong / laravel-roles

1. Go to this page and download the library: Download daijulong/laravel-roles library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

daijulong / laravel-roles example snippets

 artisan migrate
 php artisan vendor:publish --provider="Daijulong\LaravelRoles\Providers\PermissionProvider" 

class User extends Authenticatable
{
    use Notifiable, SingleRoleUserModel;
    
    // ...
    
    //定义普通用户角色(用户组)模型
    protected function roleModel()
    {
        return UserRole::class;
    }

    //定义与管理员模型关系,如果还有其他身份,也以此类推进行定义
    public function admin ()
    {
        return $this->hasOne(Admin::class);
    }   
}
permission.php



use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAdminsTable extends Migration
{
    public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->comment('用户ID');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('admins');
    }
}



use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAdminRoleTable extends Migration
{
    public function up()
    {
        Schema::create('admin_role', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->index()->comment('管理员用户ID');
            $table->unsignedInteger('role_id')->comment('角色ID');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('admin_role');
    }
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Daijulong\LaravelRoles\Traits\MultipleRoleUserModel;

class Admin extends Model
{

    use MultipleRoleUserModel;

    protected $fillable = ['user_id'];

    protected function roleModel()
    {
        return AdminRole::class;
    }

    protected function permissionUserModel()
    {
        return 'admin';
    }

    protected function relationForeignUserIdField()
    {
        return 'user_id';
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
$data
$data