laravel 如何在laravel中将多个复选框值发送到数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38822019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:16:26  来源:igfitidea点击:

How the send multiple checkbox values to database in laravel?

phplaravellaravel-5eloquentlaravel-5.2

提问by jvk

This is my view for the customer register.

这是我对客户注册的看法。

<form action="store" method="post">

    <input type="hidden" name="_token" value="{{csrf_token()}}">

    <label for="name">Name</label>
    <input type="text" name="name">
    <br>

    <label for="email">Email</label>
    <input type="text" name="email">
    <br>

    <label for="country">Country</label>
    <select name="country" id="country">
        <option value="india">India</option>
        <option value="srilanka">SriLanka</option>
        <option value="usa">USA</option>
    </select>
    <br>

    <input type="radio" name="gender" value="male">
    <label for="male">Male</label>

    <input type="radio" name="gender" value="female">
    <label for="female">Female</label>
    <br>

    <input type="checkbox" name="favorite[]" id="south" value="south">
    <label for="south">South</label>

    <input type="checkbox" name="favorite[]" id="north" value="north">
    <label for="north">North</label>

    <input type="checkbox" name="favorite[]" id="east" value="east">
    <label for="east">East</label>

    <br>

    <label for=""></label>
    <input type="submit" name="submit" value="Submit">

</form>

Well all values are going to database but the checkbox are going as array.

好吧,所有值都将进入数据库,但复选框将作为数组。

But if i remove [] in favorite. The last checkbox value is going to database.

但是,如果我在收藏夹中删除 []。最后一个复选框值将进入数据库。

This is my controller code

这是我的控制器代码

public function store(Request $request)
{
    $user= laravel::create(Request::all());
    return "data saved";
}

And this is my model

这是我的模型

class laravel extends Model
{
    protected $fillable = [
        'name', 
        "email", 
        "gender", 
        "country", 
        "favorite"
    ];
}

Can any one tell me how to send all checkbox values to database whatever customer is checked.

任何人都可以告诉我如何将所有复选框值发送到数据库,无论客户被选中。

I want to know how to edit checkbox to update.

我想知道如何编辑复选框进行更新。

Thank you in advance.

先感谢您。

采纳答案by Zayn Ali

Make a text column in your table with the name of favoriteand use this logic to store your values inside of it as csv

在表中创建一个名称为 的文本列,favorite并使用此逻辑将其中的值存储为 csv

public function store(Request $request)
{
    $request->merge([ 
        'favorite' => implode(',', (array) $request->get('favorite'))
    ]);

    laravel::create($request->all());

    return "data saved";
}