WordPress-Like Blog Laravel 5.7 and AdminLTE 3 (18) – Adding User Role to Form
In the previous part, we have created a role for the users. In this eighteenth part of creating WordPress-Like Blog using Laravel 5.7 and AdminLTE 3, we will :
- Adding Role Dropdown to Create User Form
Modify resources/views/backend/user.blade.php and add the following line to add the user role column:
1 |
<td>{{ $user->roles->first()->display_name }}</td> |
You can also add the following lines to layouts/sidebar.blade.php :
1 2 3 4 |
<div class="info"> <a href="#" class="d-block">{{ $currentUser->name }}</a> <span class="badge badge-warning">{{ $currentUser->roles->first()->display_name }}</span> </div> |
Next thing we do is to add the role option to the create user form. Add this to user/form.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 |
<div class="form-group {{ $errors->has('role') ? 'has-error' : ''}}"> {!! Form::label('role') !!} @if($user->exists && $user->id == config('cms.default_user_id')) {!! Form::hidden('role',$user->roles->first()->id) !!} <p class="form-control-static">{{ $user->roles->first()->display_name }}</p> @else {!! Form::select('role',App\Role::pluck('display_name','id'), $user->exists ? $user->roles->first()->id : null, ['class'=>'form-control','placeholder' => 'Choose a Role']) !!} @endif @if($errors->has('role')) <span class="badge badge-danger">{{ $errors->first('role') }}</span> @endif </div> |
Modify UserStoreRequest and UserUpdateRequest to add role as required.
Next, modify UsersController.php to add the attachRole to store() and update() method :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public function store(Requests\UserStoreRequest $request) { $user = User::create($request->all()); $user->attachRole($request->role); return redirect("/backend/user")->with('message', 'A New User has been added'); } public function update(Requests\UserUpdateRequest $request, $id) { $user = User::findOrFail($id); $user->update($request->all()); $user->detachRoles(); $user->attachRole($request->role); return redirect("/backend/user")->with('message', 'The User has been updated'); } |
Github commit.