This is the 7th day of my participation in the August Text Challenge.More challenges in August
1. Assign roles to users
1.1 User Model Role Association
BoLongsTo writes the following association code in the user.php model:
// Which role does the user belong to
public function role() {
return $this -> belongsTo(Role::class, 'role_id');
}
Copy the code
1.2 Adding a Permission Assignment button
<span class="label label-primary radius">
<a href="{{route('admin.user.role'.$item)}}< span style = "max-width: 100%; clear: both; min-height: 1em;Copy the code
1.3 Adding a Route assigned permission
// Assign roles to users
Route::match(['get'.'post'].'user/role/{user}'.'UserController@role')->name('user.role');
Copy the code
1.4 Adding Roles to a User Table
1.5 Method for Assigning Role Controllers
// Assign role processing
public function role(Request $request, User $user) {
// Determine if it is a POST request
if ($request -> isMethod('post')) {
$post = $this->validate($request['role_id'= >'required'
], [
'role_id.required'= >'Must choose'
]);
$user -> update($post);
return redirect(route('admin.user.index'));
}
// Read all the roles
$roleAll = Role::all();
return view('admin.user.role', compact('user'.'roleAll'));
}
Copy the code
1.6 Assigning Role Templates
Create role.blade.php under user and write the following code:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
@include('admin.common.validate');
<form action="{{route('admin.user.role', $user)}}" method="post">
@csrf
@foreach($roleAll as $item)
<div>
<label for=""> {{$item->name}}
<input type="radio" name="role_id" value="{{$item->id}}" id=""
@if($item -> id == $user -> role_id) checked @endif
>
</label>
</div>
@endforeach
<button type="submit"</button> </form> </body> </ HTML >Copy the code
1.7 the effect
If you find this article helpful on your way to learning PHP, please follow me to like and comment on it. Thank you, your blog is definitely another support for me to write.