Karthika
Karthika

Reputation: 71

How to edit and Update Checkbox values in Laravel?

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!');
}

Upvotes: 2

Views: 15834

Answers (2)

Dennis
Dennis

Reputation: 1291

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>

Upvotes: 3

Maik Lowrey
Maik Lowrey

Reputation: 17556

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')

Upvotes: 0

Related Questions