如何在 Laravel 中将数组从视图传递到控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43221151/
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
how to Pass array from view to controller in Laravel?
提问by Alimur Razi Rana
I make a form in blade.php, Here I can select multiple checkbox, and I want to pass selected input's value to controller in a array.But I failed, I can not send the data. Here is code from view. The selected input's value can be 1,2 etc;
我在blade.php中创建了一个表单,在这里我可以选择多个复选框,我想将所选输入的值传递给数组中的控制器。但是我失败了,我无法发送数据。这是视图中的代码。所选输入的值可以是 1,2 等;
<form method="post" action="{{action('votesubmitController@votesubmit')}}" class="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
@foreach($candidate_list[$post_list->id] as $candidate_list[$post_list->id])
<li>
<input type="checkbox" name= "selected[]" value= {{
$candidate_list[$post_list->id]->id }}>
<label>
<!-- some code here -->
</label>
</li>
@endforeach
<button type="submit" id="login-button">Submit</button>
</form>
Here is route-
这是路线-
Route::post('/votesubmit','votesubmitController@votesubmit');
If I write return $input in controller I find –
如果我在控制器中写 return $input 我发现 -
{"_token":"TQIUxVz0LjzM84Z7TaUPk3Y7BLZPjmXUyhXhlQfp","selected":
["1","2"]}
That's I need. I do not know how to get selected value. When I get specific route error exception happens . and says "Undefined variable: selected". Here is my Controller's code-
这就是我需要的。我不知道如何获得选定的值。当我得到特定的路由错误异常发生。并说“未定义的变量:已选择”。这是我的控制器的代码-
class votesubmitController extends Controller
{
public function votesubmit()
{
$input = Input::all();
// return $input;
foreach ($selected as $selected) {
echo $selected;
}
}
}
回答by PRADEEP PANDEY
// You can try this
class votesubmitController extends Controller
{
public function votesubmit()
{
//$input = Input::all();
//$selected = $input['selected'];
$selected = Input::get('selected');
foreach ($selected as $selected)
{
echo $selected;
}
}
}
回答by Nirbhay Kularia
Either use
$selected = $input['selected']
Or
pass it using Ajax.
要么使用
$selected = $input['selected']
要么使用 Ajax 传递它。