😇Hoàn chỉnh code User && Role

C:\xampp82\htdocs\phongkhamnet\database\migrations\2023_04_29_094915_create_roles_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   */
  public function up(): void
  {
    Schema::create('roles', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->string('guard_name');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   */
  public function down(): void
  {
    Schema::dropIfExists('roles');
  }
};

C:\xampp82\htdocs\phongkhamnet\database\migrations\2023_04_29_094923_create_permissions_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   */
  public function up(): void
  {
    Schema::create('permissions', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->string('guard_name');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   */
  public function down(): void
  {
    Schema::dropIfExists('permissions');
  }
};

C:\xampp82\htdocs\phongkhamnet\database\migrations\2023_04_29_094933_create_role_has_permissions_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   */
  public function up(): void
  {
    Schema::create('role_has_permissions', function (Blueprint $table) {
      $table->unsignedBigInteger('role_id');
      $table->unsignedBigInteger('permission_id');
    });
  }
  /**
   * Reverse the migrations.
   */
  public function down(): void
  {
    Schema::dropIfExists('role_has_permissions');
  }
};

C:\xampp82\htdocs\phongkhamnet\database\migrations\2023_04_29_094942_create_model_has_roles_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   */
  public function up(): void
  {
    Schema::create('model_has_roles', function (Blueprint $table) {
      $table->unsignedBigInteger('model_id');
      $table->string('model_type');
      $table->unsignedBigInteger('role_id');
    });
  }
  /**
   * Reverse the migrations.
   */
  public function down(): void
  {
    Schema::dropIfExists('model_has_roles');
  }
};

C:\xampp82\htdocs\phongkhamnet\database\migrations\2023_04_29_094947_create_model_has_permissions_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   */
  public function up(): void
  {
    Schema::create('model_has_permissions', function (Blueprint $table) {
      $table->unsignedBigInteger('model_id');
      $table->string('model_type');
      $table->unsignedBigInteger('permission_id');
    });
  }
  /**
   * Reverse the migrations.
   */
  public function down(): void
  {
    Schema::dropIfExists('model_has_permissions');
  }
};

C:\xampp82\htdocs\phongkhamnet\database\seeders\DatabaseSeeder.php

<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
  /**
   * Seed the application's database.
   */
  public function run(): void
  {
    $this->call([
      PermissionTableSeeder::class,
      CreateAdminUserSeeder::class
    ]);
  }
}

C:\xampp82\htdocs\phongkhamnet\database\seeders\PermissionTableSeeder.php

<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
class PermissionTableSeeder extends Seeder
{
  /**
   * Run the database seeds.
   */
  public function run(): void
  {
    $permissions = [
      'user-list',
      'user-create',
      'user-edit',
      'user-delete',
      'role-list',
      'role-create',
      'role-edit',
      'role-delete',
      'product-list',
      'product-create',
      'product-edit',
      'product-delete'
    ];
    foreach ($permissions as $permission) {
      Permission::create(['name' => $permission]);
    }
  }
}

C:\xampp82\htdocs\phongkhamnet\database\seeders\CreateAdminUserSeeder.php

<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class CreateAdminUserSeeder extends Seeder
{
  /**
   * Run the database seeds.
   */
  public function run(): void
  {
    $user = User::create([
      'name' => 'lionel',
      'email' => 'lionel@gmail.com',
      'password' => bcrypt('lionel'),
    ]);
    $role = Role::create(['name' => 'Administrator']);
    $user->assignRole($role->id);
    $permissions = Permission::pluck('id','id')->all();
    $role->syncPermissions($permissions);
  }
}

C:\xampp82\htdocs\phongkhamnet\app\Http\Controllers\UserController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class RoleController extends Controller
{
  /**
   * Display a listing of the resource.
   */
  public function index()
  {
    $roles = Role::all();
    return view('roles.index')->with(compact('roles'));
  }
  /**
   * Show the form for creating a new resource.
   */
  public function create()
  {
    $permissions = Permission::pluck('name', 'id')->all();
    return view('roles.create')->with(compact('permissions'));
  }
  /**
   * Store a newly created resource in storage.
   */
  public function store(Request $request)
  {
    $inputs = $request->all();
    $role = Role::create($inputs);
    $role->syncPermissions($inputs['permissions']);
    return redirect(route('roles.index'));
  }
  /**
   * Display the specified resource.
   */
  public function show(string $id)
  {
    $role = Role::find($id);
    return view('roles.show', compact('role'));
  }
  /**
   * Show the form for editing the specified resource.
   */
  public function edit(string $id)
  {
    $permissions = Permission::pluck('name', 'id')->all();
    $role = Role::find($id);
    $rolePermission = $role->permissions->pluck('id')->all();
    return view('roles.edit', compact('permissions', 'role', 'rolePermission'));
  }
  /**
   * Update the specified resource in storage.
   */
  public function update(Request $request, string $id)
  {
    $inputs = $request->all();
    $role = Role::find($id);
    $role->update($inputs);
    $role->syncPermissions($inputs['permissions']);
    return redirect(route('roles.index'));
  }
  /**
   * Remove the specified resource from storage.
   */
  public function destroy(string $id)
  {
    Role::find($id)->delete();
    return redirect(route('roles.index'));
  }
}

C:\xampp82\htdocs\phongkhamnet\app\Http\Controllers\RoleController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class RoleController extends Controller
{
  /**
   * Display a listing of the resource.
   */
  public function index()
  {
    $roles = Role::all();
    return view('roles.index')->with(compact('roles'));
  }
  /**
   * Show the form for creating a new resource.
   */
  public function create()
  {
    $permissions = Permission::pluck('name', 'id')->all();
    return view('roles.create')->with(compact('permissions'));
  }
  /**
   * Store a newly created resource in storage.
   */
  public function store(Request $request)
  {
    $inputs = $request->all();
    $role = Role::create($inputs);
    $role->syncPermissions($inputs['permissions']);
    return redirect(route('roles.index'));
  }
  /**
   * Display the specified resource.
   */
  public function show(string $id)
  {
    $role = Role::find($id);
    return view('roles.show', compact('role'));
  }
  /**
   * Show the form for editing the specified resource.
   */
  public function edit(string $id)
  {
    $permissions = Permission::pluck('name', 'id')->all();
    $role = Role::find($id);
    $rolePermission = $role->permissions->pluck('id')->all();
    return view('roles.edit', compact('permissions', 'role', 'rolePermission'));
  }
  /**
   * Update the specified resource in storage.
   */
  public function update(Request $request, string $id)
  {
    $inputs = $request->all();
    $role = Role::find($id);
    $role->update($inputs);
    $role->syncPermissions($inputs['permissions']);
    return redirect(route('roles.index'));
  }
  /**
   * Remove the specified resource from storage.
   */
  public function destroy(string $id)
  {
    Role::find($id)->delete();
    return redirect(route('roles.index'));
  }
}

views.users

C:\xampp82\htdocs\phongkhamnet\resources\views\users\create.blade.php

@extends('layouts.app')
@section('content')
<div class="col-md-6">
  <h1>Create User</h1>
  <a class="btn btn-primary" href="{{ route('users.index') }}" role="button">Back</a>
  {!! Form::open(["class"=>"form-horizontal","method"=>"POST","route"=>["users.store"]]) !!}
  {!! Form::label("name", "Name") !!}
  {!! Form::text('name', '', ["class"=>"form-control"]) !!}
  {!! Form::label("email", "Email") !!}
  {!! Form::email("email", "", ["class"=>"form-control"]) !!}
  {!! Form::label("[password]", "Password") !!}
  {!! Form::password("password", ["class"=>"form-control"]) !!}
  {!! Form::label("roles", "Roles") !!}
  {!! Form::select("roles[]",$roles, null, ["multiple"=>true,"class"=>"form-control"]) !!}
  {!! Form::submit("Create", ["class"=>"d-block btn btn-success"]) !!}
  {!! Form::close() !!}
</div>
@endsection

C:\xampp82\htdocs\phongkhamnet\resources\views\users\edit.blade.php

@extends('layouts.app')
@section('content')
<div class="col-md-6">
  <h1>Edit User</h1>
  <a class="btn btn-primary" href="{{ route('users.index') }}" role="button">Back</a>
  {!! Form::open(["class"=>"form-horizontal","method"=>"PATCH","route"=>["users.update",$user->id]]) !!}
  {!! Form::label("name", "Name") !!}
  {!! Form::text('name', $user->name, ["class"=>"form-control"]) !!}
  {!! Form::label("email", "Email") !!}
  {!! Form::email("email", $user->email, ["class"=>"form-control"]) !!}
  {!! Form::label("[password]", "Password") !!}
  {!! Form::password("password", ["class"=>"form-control"]) !!}
  {!! Form::label("roles", "Roles") !!}
  {!! Form::select('roles[]', $roles,$userRole, array('class' => 'form-control','multiple')) !!}
  {!! Form::submit("Edit", ["class"=>"d-block btn btn-success"]) !!}
  {!! Form::close() !!}
</div>
@endsection

C:\xampp82\htdocs\phongkhamnet\resources\views\users\index.blade.php

@extends('layouts.app')
@section('content')
<div class="col-md-12">
  <h1>User Management</h1>
  @can('user-create')
    <a class="btn btn-primary" href="{{ route('users.create') }}" role="button">Create User</a>
  @endcan
  <div class="table-responsive">
    <table class="table table-primary">
      <thead>
        <tr>
          <th scope="col">No</th>
          <th scope="col">Name</th>
          <th scope="col">Email</th>
          <th scope="col">Actions</th>
        </tr>
      </thead>
      <tbody>
        @foreach($users as $user)
          <tr>
            <td scope="row">1</td>
            <td>{{ $user->name }}</td>
            <td>{{ $user->email }}</td>
            <td>
              <a class="btn btn-primary" href="{{ route('users.show',$user->id) }}" role="button">Show</a>
              @can('user-edit')
                <a class="btn btn-primary" href="{{ route('users.edit',$user->id) }}" role="button">Edit</a>
              @endcan
              {!! Form::open(["method"=>"DELETE","route"=>["users.destroy",$user->id],"class"=>"d-inline"]) !!}
              {!! Form::submit("Delete", ["class"=>"btn btn-danger"]) !!}
              {!! Form::close() !!}
            </td>
          </tr>
        @endforeach
      </tbody>
    </table>
  </div>
</div>
@endsection

C:\xampp82\htdocs\phongkhamnet\resources\views\users\show.blade.php

@extends('layouts.app')
@section('content')
<div class="col-md-12">
  <a class="btn btn-primary" href="{{ route('users.index') }}" role="button">Back</a>
  <p>Name: {{ $user->name }}</p>
  <p>Email: {{ $user->email }}</p>
  <p>Roles:
    @foreach($user->roles as $role)
    <span class="badge bg-secondary">{{ $role->name }}</span>
    @endforeach
  </p>
</div>
@endsection

views.roles

C:\xampp82\htdocs\phongkhamnet\resources\views\roles\create.blade.php

@extends('layouts.app')
@section('content')
<div class="col-md-6">
  <h1>Create User</h1>
  <a class="btn btn-primary" href="{{ route('roles.index') }}" role="button">Back</a>
  {!! Form::open(["class"=>"form-horizontal","method"=>"POST","route"=>["roles.store"]]) !!}
  {!! Form::label("name", "Name") !!}
  {!! Form::text('name', '', ["class"=>"form-control"]) !!}
  {!! Form::label("permissions", "Permissionss") !!}
  {!! Form::select("permissions[]",$permissions, null, ["multiple"=>true,"class"=>"form-control"]) !!}
  {!! Form::submit("Create", ["class"=>"d-block btn btn-success"]) !!}
  {!! Form::close() !!}
</div>
@endsection

C:\xampp82\htdocs\phongkhamnet\resources\views\roles\edit.blade.php

@extends('layouts.app')
@section('content')
<div class="col-md-6">
  <h1>Edit User</h1>
  <a class="btn btn-primary" href="{{ route('roles.index') }}" role="button">Back</a>
  {!! Form::open(["class"=>"form-horizontal","method"=>"PATCH","route"=>["roles.update",$role->id]]) !!}
  {!! Form::label("name", "Name") !!}
  {!! Form::text('name', $role->name, ["class"=>"form-control"]) !!}
  {!! Form::label("permissions", "Permissionss") !!}
  {!! Form::select("permissions[]",$permissions, $rolePermission, ["multiple"=>true,"class"=>"form-control"]) !!}
  {!! Form::submit("Edit", ["class"=>"d-block btn btn-success"]) !!}
  {!! Form::close() !!}
</div>
@endsection

C:\xampp82\htdocs\phongkhamnet\resources\views\roles\index.blade.php

@extends('layouts.app')
@section('content')
<div class="col-md-6">
  <h1>Roles Management</h1>
  @can('role-create')
  <a class="btn btn-primary" href="{{ route('roles.create') }}" role="button">Create Role</a>
  @endcan
  <div class="table-responsive">
    <table class="table table-primary">
      <thead>
        <tr>
          <th scope="col">No</th>
          <th scope="col">Name</th>
          <th scope="col">Actions</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($roles as $key => $role)
        <tr>
          <td scope="row">{{ $key + 1 }}</td>
          <td>{{ $role->name }}</td>
          <td>
            <a href="{{ route('roles.show', $role->id) }}" role="button" class="btn btn-primary">Show</a>
            @can('role-edit')
              <a href="{{ route('roles.edit', $role->id) }}" role="button" class="btn btn-primary">Edit</a>
            @endcan
            @can('role-delete')
            {!! Form::open(["method"=>"DELETE","route"=>["roles.destroy",$role->id],"class"=>"d-inline"]) !!}
              {!! Form::submit("Delete", ["class"=>"btn btn-danger"]) !!}
            {!! Form::close() !!}
            @endcan
          </td>
        </tr>
        @endforeach
      </tbody>
    </table>
  </div>
</div>
@endsection

C:\xampp82\htdocs\phongkhamnet\resources\views\roles\show.blade.php

@extends('layouts.app')
@section('content')
<div class="col-md-12">
  <a class="btn btn-primary" href="{{ route('roles.index') }}" role="button">Back</a>
  <p>Name: {{ $role->name }}</p>
  <p>Permissions:
    @foreach($role->permissions as $permission)
    <span class="badge bg-secondary">{{ $permission->name }}</span>
    @endforeach
  </p>
</div>
@endsection

Last updated