简体   繁体   中英

How to store multiple checkbox values to database in Laravel?

I need to store checkbox values into the database. I have tried so many examples, but still am not able to do that, Here I will give you my code and give me the solution for this.

My Blade File

<div class="form-group row">
    <label for="hobbies" class="col-md-4 col-form-label text-md-right">Hobbies</label>
    <div class="col-md-6">
        <input type="checkbox" name="hobbies[]" value="Readbooks"/> Readbooks
        <input type="checkbox" name="hobbies[]" value="Games"/> Games
        <input type="checkbox" name="hobbies[]" value="Music"/> Music
        @if ($errors->has('hobbies'))
            <span class="text-danger">{{ $errors->first('hobbies') }}</span>
        @endif
    </div>
</div>

My Controller File

public function postRegistration(Request $request)
{   
    $data = $request->all();
    $check = $this->create($data);

    return redirect("login")->withSuccess('Great! please login.');
}

public function create(array $data)
{
    return User::create([
        'hobbies' => $data->implode([',', (array) $data->get('hobbies')]),
     ]);
  }

Error:Call to a member function implode() on array

This is not how you use the implode method. And like the error says; you try to call a method on an array, because $data is an array and not an object.

And last, $data->get('hobbies') will also cause you problems, because the get() helper is not working on an array.

This is what you need:

return User::create([
    'hobbies' => implode(',', (array) $data['hobbies']),
]);

When you have inputs like:

<input type="checkbox" name="hobbies[]" value="Readbooks"/> Readbooks
<input type="checkbox" name="hobbies[]" value="Games"/> Games
<input type="checkbox" name="hobbies[]" value="Music"/> Music

The POST data received by the server includes hobbies as an array. You can confirm this by inspecting the received request in your controller:

public function postRegistration(Request $request) {
    dd($request);
}

Since $request->hobbies is already an array, there is no need to cast it with (array) .

In the code you've shown, you are trying to implode() your hobbies. implode() generates a string, so if the hobbies field you are trying to populate in the database is a string, you simply need to implode that received array of hobbies :

// Will generate a string like: "Readbooks,Music"
implode(',', $request->hobbies);

Putting it into your code:

public function create($data) {
    return User::create(['hobbies' => implode(',', $data->hobbies)];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM