I use Bootstrap Modal for editing user roles. But without using form. just some Checkbox and a buttom for submitting operation. I use ajax to send data to coontroller. But in controller side when I want to use Eloquent methods, I get errros like 404 and 500. I really confused. I worked on it for more then 5 hours.
View :
<div class="modal" id="rolesEditModal" role="dialog" > <!--tabindex="-1"-->
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Roles</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert" id="imgMessage" style="display:none"></div>
<div class="modal-body bg-gray">
<div class="editRolesElement">
<label for="modalTitle" id="userRolesLabel"><span> </span> User Roles </label>
<!-- checkbox -->
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="sysAdminCheckbox" id="checkbox1">
<label class="form-check-label" for="checkbox1" style="font-weight: bold;color: black">System Admin</label>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="homePageAdminCheckbox" id="checkbox2">
<label class="form-check-label" for="checkbox2">HomaPage Admin</label>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="aboutUsAdminCheckbox" id="checkbox3">
<label class="form-check-label" for="checkbox3">Aboutus Admin</label>
</div>
<div id="editmessage" style="display:none"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button id="submitModal" type="button" class="btn btn-success" data-dismiss="modal">save</button>
<!--<input type="submit" id="submitModal" class="btn btn-primary" value="Save">--><!--Save changes</button>-->
</div>
script :
<pre><code><script type="text/javascript">
$(document).ready( function () {
$("#submitModal").click(function(){
$('#editmessage').hide();
var systemAdmin = 0;
var homeAdmin = 0;
var aboutUsAdmin = 0;
var portfolioAdmin = 0;
var featuresAdmin = 0;
var contactusAdmin = 0;
var commentAdmin = 0 ;
if($('#checkbox1:checked').val())
{ systemAdmin = 1; } else { systemAdmin = 0; }
if($('#checkbox2:checked').val())
{ homeAdmin = 1; } else { homeAdmin = 0; }
if($('#checkbox3:checked').val())
{ aboutUsAdmin = 1; } else { aboutUsAdmin = 0; }
if($('#checkbox4:checked').val())
{ portfolioAdmin = 1; } else { portfolioAdmin = 0; }
if($('#checkbox5checked').val())
{ featuresAdmin = 1; } else { featuresAdmin = 0; }
if($('#checkbox6:checked').val())
{ contactusAdmin = 1; } else { contactusAdmin = 0; }
if($('#checkbox7:checked').val())
{ commentAdmin = 1; } else { commentAdmin = 0; }
var A_url='';
A_url = "{{ route('userManagement.editRoles') }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : A_url,
data :
{
userId : $(this).data('userid'),
systemAdmin : systemAdmin,
homeAdmin : homeAdmin,
aboutUsAdmin : aboutUsAdmin,
portfolioAdmin : portfolioAdmin,
featuresAdmin : featuresAdmin,
contactusAdmin : contactusAdmin,
commentAdmin : commentAdmin
},
type : 'post',
fail: function(data){
var incerttxt = '<div class="alert alert-danger" role="alert">Server error</div>';
$('#editmessage').html(incerttxt);
$('#editmessage').fadeIn();
},
success : function( data ) {
//updateUserList_afterEditRoles(data,selectedButton);
console.log(data);
}
});
$('#rolesEditModal').modal('hide');
});
the route :
Route::post('editRoles', 'UserManagementController@editRoles')->name('userManagement.editRoles');
controller :
<pre><code>public function editRoles(Request $request)
{
$userId=$request["userId"];
//$findedUser = User::find($userId)->roles()->orderBy('id')->get();
$findedUser = User::findorfail($request['userId']);
//$findedUser->roles()->detach();
//$findedUser->roles()->attach($roleId);
$assignedRoles = array();
if ($request["systemAdmin"]==="1")
{ array_push($assignedRoles, 1); }
if ($request["homeAdmin"]==="1")
{ array_push($assignedRoles, 2); }
if ($request["aboutUsAdmin"]==="1")
{ array_push($assignedRoles, 3); }
if ($request["portfolioAdmin"]==="1")
{ array_push($assignedRoles, 4); }
if ($request["featuresAdmin"]==="1")
{ array_push($assignedRoles, 5); }
if ($request["contactusAdmin"]==="1")
{ array_push($assignedRoles, 6); }
if ($request["commentAdmin"]==="1")
{ array_push($assignedRoles, 7); }
$findedUser->roles()->sync([2,3,4]/*$assignedRoles*/);
return ($findedUser);
}
</code></pre>
I write the whole implementation without checking. Hope this will work well for you. Did just small changes and improvements. So you can customize if you want..
BLADE WITH SCRIPT
<div class="modal" id="rolesEditModal" role="dialog" >
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Roles</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert" id="imgMessage" style="display:none"></div>
<div class="modal-body bg-gray">
<div class="editRolesElement">
<label for="modalTitle" id="userRolesLabel"><span> </span> User Roles </label>
@foreach($roles as $role)
<div class="form-group form-check">
<input data-id="{{ $role->id }}" type="checkbox" class="form-check-input" id="checkbox_{{ $role->id }}">
<label class="form-check-label" for="checkbox_{{ $role->id }}">{{ $role->name }}</label>
</div>
@endforeach
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button id="submitModal" type="button" class="btn btn-success" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
<script>
function getRoles() {
let roles = {};
$('#rolesEditModal .form-check-input').each(function(i) {
roles [$(this).data('id')] = $(this).prop('checked');
});
return roles;
}
function submitRoles(roles) {
$.ajax({
data: {
_token: "{{ csrf_token() }}",
user_id: "{{ $user->id }}",
roles: roles
},
url: "{{ route('userManagement.editRoles') }}",
type: "POST"
}).done(function (data) {
console.log(data.message);
}).fail(function (jqXHR, ajaxOptions, thrownError) {
console.log("Server error!");
});
}
function destructCheckboxes() {
$('#rolesEditModal .form-check-input').prop('checked', false);
}
$("#submitModal").on('click', function() {
let roles = getRoles();
submitRoles(roles);
destructCheckboxes();
$('#rolesEditModal').modal('hide');
});
</script>
ROUTE
// here you just need to write one more route, which from action will return $roles collection and $user (or $users for your case with foreach in blade) object to the view
Route::post('editRoles', 'UserManagementController@editRoles')->name('userManagement.editRoles');
CONTROLLER
public function editRoles(Request $request)
{
$user = User::findOrfail($request->get('user_id'));
$roles = Role::whereIn('id', $request->get('roles'))->get();
$user->roles()->delete();
$user->roles()->saveMany($roles);
return response()->json([
'success' => true,
'message' => "Roles successfully assigned to the user.",
], 200);
}
NEW UPDATES
In your controller you also have some method for getting your page, right? I think in your blade you have one $user (for single user's page) or $users (for showing multiple users). So I don't know what exactly in your blade, but you can use one of these methods for your specific case, or both them if you need:
public function singleUserPage($user_id)
{
$user = User::findOrFail($user_id);
$roles = Role::all();
return view('user-management', [ // view for single user
'user' => $user,
'roles' => $roles,
]);
}
// for this you need to loop over on each user in the view, and it will have a same functionality
public function multipleUsersPage()
{
$users = User::all();
$roles = Role::all();
return view('users-management', [ // view for multiple users
'users' => $users,
'roles' => $roles,
]);
}
You will have (or already have) appropriate routes for this methods like this:
Route::get('user/{user_id}', 'UserManagementController@singleUserPage')->name('user_page');
Route::get('users', 'UserManagementController@multipleUsersPage')->name('users_page');
So if you getting the $user as "undefined", you need to send that from controller to the page at first (as I in two methods on the top).