Show checkbox checked from database in laravel - php

I'm using Laratrust package for ACL in my application. I'm trying to edit roles (assign permissions to role) using checkbox. And want get already assigned permission checkbox state checked from database.
Code in RoleController.php
public function edit($id)
{
$role = Role::where('id', $id)->with('permissions')->first();
$permissions = Permission::all();
return view('admin.manage.roles.edit')->withRole($role)->withPermissions($permissions);
}
Below is the code what I have tried:
#foreach($permissions as $permission)
<div class="checkbox checkbox-styled">
<label>
<input type="checkbox" name="permissions[]" value="{{$permission->id}}"
{{ $role->permissions->pluck('id') == $permission->id ? 'checked' : '' }}
>
<span>{{$permission->display_name}} <em>({{$permission->description}})</em></span>
</label>
</div>
#endforeach
The code is throwing error
Object of class Illuminate\Support\Collection could not be converted to int
I had tried:
{{ $role->permissions->id == $permission->id ? 'checked' : '' }}
This throws error:
Property [id] does not exist on this collection instance
When I do {{dd($role->permissions)}}: The following output was given:
I would be very thankful if anyone could point-out mistake I'm doing here.

Your code will not work because you are trying to compare array with a string, which is impossible. you can use php in_array function to check whether your permission exist for the current permission or not
I think you are trying to check all the permission which already exist for the specific roles. correct me if i am wrong.
Try this
<input type="checkbox" name="permissions[]" value="{{$permission->id}}"
#if($role->permissions) #if(in_array($permission->id, $role->permissions->pluck('id')) checked #endif #endif>
Hope this will help :)

Easiest way to do is to check in collection using contain
#if($role->permissions->contains($permission->id)) checked=checked #endif
<input type="checkbox" name="permissions[]" value="{{$permission->id}}"
{{ #if($role->permissions->contains($permission->id)) checked=checked #endif }}
>

Another short method.
<input type="checkbox" name="permissions[]" value="{{ $permission->id }}"
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}>

Related

Undefined variable in laravel blade partial view error

I am getting the following error when loading a page:
Undefined variable: userIds
However, the variavle is reaching the partial given when I try {{ isset($userIds) ? 'Yes' : 'No' }} it returns 'Yes' when the block of code is reached.
The error occurs with the variable $userIds in the following input type:
</li>
#foreach ($users as $index => $user)
<li class="list-group-item"
style="{{ (isset($usersFiltered) && is_array($usersFiltered) && !in_array($user->id, $usersFiltered) ) ?
'display: none;' : ''}}">
<div class="checkbox">
<label>
<input type="checkbox" class="awe-selectable" id="users[{{ $index }}]" name="users[{{ $index }}]"
value="{{ $user->id }}" {{ in_array($user->id,$userIds) ? 'checked' : '' }}>
<label for="users[{{ $index }}]">{{ $user->name }}</label>
</label>
</div>
</li>
#endforeach
My controller code sending the variable to the partial:
return view('core::admin.groups.partials._users_form', [
'group' => $group,
'users' => $users,
'usersFiltered' => $usersFiltered,
'userIds' => $userIds,
]);
Is it a syntax mistake? If I replace $userIds by any of the other variables, those too will return the same "undefined" error (f.e. with $usersFiltered)
Thanks in advance, will edit the post with more information as needed.
Solved!
The issue was that when the page was rendered, the variable was not defined in the main page render (/create), only in the method that rendered the partial, so when I was opening the main window, the variable was not yet defined because it was only received from the controller once a filter was applied.
Sollution:
/**
* GET: /admin/security/groups/create
*/
public function create()
{
**$userIds = !empty($request['userIds']) ? $request['userIds'] : [];**
(...)
return view('core::admin.groups.create', [
'group' => new Group,
**'userIds' => $userIds,**
'users' => $users,
'isCreating' => true,
]);
the syntax looks good to me, but I would suggest to you to do this:
// in your controller
foreach ($users as $user) {
$user->checked = false;
if ((is_array($userIds) and !empty($userIds)) and in_array($user->id, $userIds)) {
$user->checked = true;
}
}
now there is no need to send the $userIds to the view, since you fixed it in the controller.
// in your view
<input type="checkbox" class="awe-selectable" id="users[{{ $index }}]" name="users[{{ $index }}]" value="{{ $user->id }}" {{ ($user->checked) ? 'checked' : '' }}>
Happy coding!

Laravel 5.7 - Undefined offset: 1

I'm new in Laravel and it is my first question.
I have 3 tables:
categories: id, name (at the moment 2 items)
variants: id, name
category_variant: id, category_id, variant_id; <--
Every variant has 1 or 2 categories
In the VariantController I have following code:
public function edit($id)
{
$variant = Variant::where('id', $id)->with('categories')->first();
$categories = Category::all();
return view('admin.variant.edit', compact('variant', 'categories'));
}
In the edit.blade.php I have following html:
#foreach ($categories as $key=>$category)
<div class="form-group form-float">
#if (isset($variant->categories[$key]->pivot->category_id)) <-- I think here is the problem
<input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" {{ $category->id == $variant->categories[$key]->pivot->category_id ? 'checked' : ''}} >
<label for="wb">{{ $category->name}}</label>
#else
<input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}">
<label for="wb">{{ $category->name}}</label>
#endif
</div>
#endforeach
I want to know which category was checked in the checkbox. If the variant has all 2 categories everthing is ok but if the user has chosen only one category I get an error
Undefined offset: 1 (View: /shui/resources/views/admin/variant/edit.blade.php)
How can I solve this problem?
Thanks in advance
Dimi
You can use the power of collection:
#if($variant->categories->contains($category))
{{-- You does not need to test a second time to know if you need to "check" --}}
<input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" checked >
<label for="wb">{{ $category->name}}</label>
#else
{{-- Do stuff --}}
#endif
Or simpler. Remove the first #if
<input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" $variant->categories->contains($category)? 'checked' : '' >
<label for="wb">{{ $category->name}}</label>
Also in you Controller, you can simplify
$variant = Variant::where('id', $id)->with('categories')->first();
with
$variant = Variant::with('categories')->find($id);
// Or better, Laravel throws a 404 error when the id doesn't exists
$variant = Variant::with('categories')->findOrFail($id);

Laravel - Setting Checked Property of Checkbox From Returned Array Input

I'm having a problem where I'm trying to handle a
return Redirect::to('page')->withInput();
call while using an array of checkboxes. Basically, if my validator fails, I want to return back, display some errors and repopulate inputs with their value. Here are the inputs I'm having difficulty with.
<div class="row">
<div class="col-xs-12">
<label class="checkbox-inline">
<input type="checkbox" name="rms_cs[]" value="Marshall and Swift Property Valuation" {{ (Input::old("rms_cs[]") == "Marshall and Swift Property Valuation") ? "checked":"" }}> Marshall & Swift Property Valuation
</label>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<label class="checkbox-inline">
<input type="checkbox" name="rms_cs[]" value="Premises Liability Survey" {{ (Input::old("rms_cs[]") == "Premises Liability Survey") ? "checked":"" }}> Premises Liability Survey
</label>
</div>
</div>
So, basically, I have multiple checkboxes, each with name="rms_cs[]" and value="something". How would I go about setting the checked property to checked when Input is returned?
Note: I have lots of text boxes and radio buttons that work fine, so I know that the issue doesn't lie with anything besides Input::old("rms_cs[]"). I think the issue is that rms_cs[] is an indexed array; ie rms_cs[0] = "Something" and not rms_cs["Premises Liability Survey"] = "Something"
If anyone could shed some light on this/provide a better way to handle something like this, that would be great.
You may use Laravel Form&HTML builder to achieve what you want, plus doing some extra work in your controller.
In your controller, you manually construct a checkbox array as follows:
$boxes = array();
$checkboxInput = Input::get('box');
foreach ($checkboxInput as $box) {
$boxes[$box] = true;
}
and then return with $boxes:
return Redirect::back()->withInput()->with('boxes',$boxes);
Next in your blade file, you use the Form class to set default checked value to either true or false like this:
{{Form::checkbox('box[]', 'box1', isset($boxes['box1']) && $boxes['box1'])}}
{{Form::checkbox('box[]', 'box2', isset($boxes['box2']) && $boxes['box2'])}}
And now you should see some checkboxes have been checked.
So, I ended up figuring this out. I changed
name="rms_ssp[]"
on each checkbox to:
name="rms_ssp[epis]"
name="rms_ssp[mrp]"
etc, so the array was no longer indexed. Then, I made a variable out of the old input:
<?php $rms_ssp = Input::old('rms_ssp'); ?>
And added this check in each of the checkboxes:
{{ (isset($rms_ssp['epis'])) ? "checked":"" }}
{{ (isset($rms_ssp['mrp'])) ? "checked":"" }}
And that did the trick.

How to show checkboxes as checked when values are set in the database in Laravel

I'm setting up entrust and trying to manage roles via an edit users page. I have pulled the list of available roles as well as the roles that the user is already assigned to and have them passed to the view as $roles and $assignedRoles.
The problem I'm having is getting the form to show the already assigned roles ($assignedRoles) as checked and the un-assigned roles (remainder of $roles) as not checked.
$roles looks like
[{"id":1,"name":"Admin","created_at":"2014-09-15 14:26:24","updated_at":"2014-09-15 14:26:24"},{"id":2,"name":"Pastor","created_at":"2014-09-15 14:26:34","updated_at":"2014-09-15 14:26:34"},{"id":3,"name":"Elder","created_at":"2014-09-15 14:26:43","updated_at":"2014-09-15 14:26:43"},{"id":4,"name":"Ministry Leader","created_at":"2014-09-15 14:26:55","updated_at":"2014-09-15 14:26:55"}]
and $userRoles looks like
[{"id":1,"name":"Admin","created_at":"2014-09-15 14:26:24","updated_at":"2014-09-15 14:26:24","pivot":{"user_id":1,"role_id":1}}]
I am iterating through the available roles in the view using
#foreach ($roles as $role)
{{ Form::checkbox('role[]', $role->id) }}
{{ Form::label('role', $role->name) }}<br>
#endforeach
My problem is that I do not know how I can make it so that when viewing the form it will show which roles are already set as per $userRoles (above).
First you make an array with all data
<?php
$all_data = array();
foreach($roles as $role){
$all_data[] = $role->id;
}
?>
Now you create checkbox
#foreach ($roles as $role)
{{ Form::checkbox('role[]', $role->id, in_array($role->id, $all_data)) }}
{{ Form::label('role', $role->name) }}<br>
#endforeach
In Controller
$user = User::find($id);
$allRoles = Role::all();
$assignedRoles = $user->roles->pluck('id')->toArray();
In View
<div class="form-group row" id="assign_hostel_fees">
<label for="inputEmail3" class="col-sm-3 control-label">Select Roles</label>
<div class="col-sm-9">
#foreach($allRoles as $role)
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="roles[]" value="{{$role->id}}" {{in_array($role->id,$assignedRoles)?'checked':''}}>
{{$role->name}}
</label>
</div>
#endforeach
</div>
</div>
this might help you -
{{ Form::checkbox('agree', 1, true) }}
will generate -
<input checked="checked" name="agree" type="checkbox" value="1">
the third parameter defines if it will be checked or not. depending on the data(check the role id of $userRoles with $roles) generate a variable with true or false value.

Form Model Binding for checkboxes

I'm using Laravel 4.1 and in my app I need to show a form with pre filled checkboxes. But I try to do it with using Form Model Binding, it doesn't work.
{{ Form::model($user, array('route' => 'settings-notify')) }}
<div class="formRow form-horizontal_row">
{{ Form::checkbox('notify_visit', '1') }}
</div>
<div class="formRow form-horizontal_row">
{{ Form::checkbox('notify_rate', '1') }}
</div>
<div class="formSubmit">
{{ Form::submit('Save') }}
</div>
{{ Form::close() }}
Is there any way to make it working?
I ended up handling this in my controller because as #Ladislav Maxa says in their comment to #Antonio Carlos Ribeiro the database never updates. This is because empty checkboxes are not submitted with the form so no 'unchecked' value is available for updating the database.
The solution I used is to check for the existence of the field in the get object. If it's there the box was checked.
$notify_rate = Input::get('notify_rate') ? 1 : 0;
$data['notify_rate'] = $notify_rate;
Another way I have done this before was to create a text input with the same name and a value of 0 before the checkbox. If the checkbox is unticked the text input value is submitted, if the checkbox is ticked it's value is used.
<input name="notify_rate" type="text" value="0">
<input name="notify_rate" type="checkbox" value="1">
That's probably not valid HTML though and I prefer dealing with this server side.
Works fine for me, here's a test I just did here:
Route::get('test', function() {
$user = User::where('email','myemail#domain.com')->first();
Form::model($user);
$user->notify_rate = true;
echo e(Form::checkbox('notify_rate'));
$user->notify_rate = false;
echo e(Form::checkbox('notify_rate'));
});
This is what I got:
<input checked="checked" name="notify_rate" type="checkbox" value="1">
<input name="notify_rate" type="checkbox" value="1">

Categories