I am beginner in larval and I want to edit and update checkbox values. Now I can able to store checkbox values, but when I click edit it's not showing checked values in edit view. So please help me how can I resolve this solution. Here I will give you my code.
My Blade File
<input type="checkbox" name="hobbies" id="readbooks" value="Readbooks" {{ $users->hobbies=="Readbooks"? 'checked':'' }}>Readbooks
<input type="checkbox" name="hobbies" id="music" value="Music"{{ $users->hobbies=="Music"? 'checked':'' }}/> Music
<input type="checkbox" name="hobbies" id="games" value="Games" {{ $users->hobbies=="Games"? 'checked':'' }}/> Games
My controller File
public function edit($id)
{
$users = User::find($id);
echo $users;
return view('edit',['users'=>$users]);
}
public function updateUser(Request $request, $id)
{
User::whereId($id)->update($validatedData);
return redirect("view")->withSuccess('User! Successfully Updated!');
}
CodePudding user response:
I think you need to give the hobbies as array back to the view and then check if the value of the input is in the array of hobbies:
First return the user to the view:
public function edit($id)
{
$users = User::find($id);
return view('edit', [
'users' => $users,
'hobbies' => explode(',', $user->hobbies)
]);
}
public function updateUser(Request $request, $id)
{
User::find($id)->update($request->all());
return redirect("view")->withSuccess('User Successfully Updated!');
}
Then in your view
<form action="{{ url('updateText/'.$users->id) }}" enctype="multipart/form-data" method="POST">
<input type="checkbox" name="hobbies[]" id="readbooks" value="Readbooks" {{ in_array('Readbooks', $hobbies) ? 'checked' : '' }}>Readbooks
<input type="checkbox" name="hobbies[]" id="music" value="Music" {{ in_array('Music', $hobbies) ? 'checked' : '' }}>Music
<input type="checkbox" name="hobbies[]" id="games" value="Games" {{ in_array('Games', $hobbies) ? 'checked' : '' }}>Games
</form>
CodePudding user response:
The code you have looks fine. but as @OMiShah correctly pointed out, the values may have been stored in an array or in a comma-separated string in the database. since we don't know this now, two possibilities to build the condition:
in_array("Music", $users->hobbies)
or
str_contains($users->hobbies, 'Music')
CodePudding user response:
=>please set old value and using if condition it can be check value set try this it will be work.
<input type="checkbox" name="hobbies" id="readbooks" value="{{old('hobbies',$users->hobbies)}}" @if($users->hobbies== 'Readbooks') checked="checked" @endif/>Readbooks
<input type="checkbox" name="hobbies" id="music" value="{{old('hobbies',$users->hobbies)}}" @if($users->hobbies== 'Music') checked="checked" @endif/> Music
<input type="checkbox" name="hobbies" id="games" value="{{old('hobbies',$users->hobbies)}}" @if($users->hobbies== 'Games') checked="checked" @endif/> Games