I would like to create User Admin and Super admin roles in my project. I'm trying to learn by myself.
create_roles_table.php
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
create_roles_user_table.php
class CreateRoleUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
App\User.php
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this
->belongsToMany('App\Role')
->withTimestamps();
}
public function users()
{
return $this
->belongsToMany('App\User')
->withTimestamps();
}
public function authorizeRoles($roles)
{
if ($this->hasAnyRole($roles)) {
return true;
}
abort(401, 'This action is unauthorized.');
}
public function hasAnyRole($roles)
{
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
} else {
if ($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role)
{
if ($this->roles()->where(‘name’, $role)->first()) {
return true;
}
return false;
}
}
Middleware\CheckRole.php
class CheckRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
abort(401, 'This action is unauthorized.');
}
return $next($request);
}
}
AdminController
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('role:ROLE_ADMIN');
}
public function index()
{
return view('admin.home');
}
}
views/admin/home.blade.php
@extends('layouts.app')
@section('content')
<div >
<div >
<div >
<div >
<div >Admin Dashboard</div>
<div >
@if (session('status'))
<div >
{{ session('status') }}
</div>
@endif
This is Admin Dashboard. You must be privileged to be here !
</div>
</div>
</div>
</div>
</div>
@endsection
route
Route::get('/', function () {
return view('auth/login');
});
Auth::routes(['verify' => true]);
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/admin', 'AdminController@index');
Route::get('/superadmin', 'SuperAdminController@index');
Route::resource('posts', PostController::class);
I try to do in this project so that there is the user the administrator and the super admin. I added what you see in the code but I feel like I'm missing things, I don't know what to add in the migration of user and role so that it can identify if it's an admin user or super admin. Currently I register, I register as a user but I would like to do so that if in the database a user is admin that he has access to the pages for admins and the other pages, while the user has the access as the user space. What am I missing in my code to make it work?
CodePudding user response:
First of all, Let me explain some basic things.
Users -> The users who are going to access your application.(i.e., superadminname, adminname)
Roles -> The roles who will be under your application(Super admin, Admin). There will be multiple users under the same role. The roles will be mapped with users.
Permissions -> The permission that is accessible for the particular role('Create user', 'Edit user', 'Delete User'). The super admin can have all the 3 privileges. But the admin can have only create and edit option and not the delete option. The permissions will be mapped to roles.
If you need only roles, The migrations should be roles and role_users. If you need permissions also, Then you can go with permissions and permission_role.
// Schema to create roles table
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
// Schema to create role_users table
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['user_id', 'role_id']);
});
// Schema to create permissions table
Schema::create('permissions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
// Schema to create permission_role table
Schema::create('permission_role', function (Blueprint $table) {
$table->unsignedBigInteger('permission_id');
$table->unsignedBigInteger('role_id');
$table->foreign('permission_id')->references('id')->on('permissions')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});