【发布时间】:2021-06-14 18:52:29
【问题描述】:
您好,我正在 Laravel 中进行基于角色的身份验证,一切正常,但我在角色部分有问题。 我想从我的角色列表页面中隐藏编辑和删除等操作按钮,那些已分配给用户的角色无法删除,但尚未分配给用户的其他角色可以删除。
角色迁移
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('role_typ');
$table->string('role_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
用户迁移
class AddColumnsToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
});
}
用户模型
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
角色控制器
// Role Management
public function Rolelist()
{
$roles = Role::paginate(10);
return view('admin.roles', compact('roles'));
}
角色列表刀片页面
<div class="card">
<div class="card-header">
<h3 class="card-title">All Role List</h3>
<div class="card-tools">
<a href="{{ route('roleform') }}" class="btn btn-block btn-success btn-sm">Add Role <i
class="fas fa-user-plus"></i></a>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>ID</th>
<th>Role Name</th>
<th>Role Type</th>
<th>Created</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($roles as $role)
<tr>
<td>{{ $role->id }}</td>
<td>{{ $role->role_name }}</td>
<td>{{ $role->role_typ }}</td>
<td> {{ \Carbon\Carbon::createFromTimeStamp(strtotime($role->created_at))->diffForHumans() }}
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
【问题讨论】:
-
Welcome to SO ...隐藏你需要在你的模型中创建关系你添加了吗?
-
最简单的方法是创建一个 Blade 指令并使用它来显示基于角色的内容。请查看:laravel.com/docs/8.x/blade#custom-if-statements
-
我知道,但如何使该逻辑仅显示与用户模型没有任何关系的角色的操作按钮
-
@if($role->id = 1) @else
-
你为什么不试试这个Spatie role permission