循环复选框形式Laravel

时间:2015-08-06 09:28:43

标签: php forms laravel foreach

我想我在这里错过了一些小事。我是Laravel和php的新手。当我尝试使用foreach循环提交此表单时,我收到错误。每个兴趣都应该循环到我的表中的新插入。你能帮我指导一下这个堆栈溢出吗,我已经阅读了其他一些解决方案,但是不太明白如何将它们应用到我的问题中?这就是我拥有的一切:

错误:

ErrorException in InterestController.php line 45:
Trying to get property of non-object

$ interests = $ inputs-> interest; ------->第45行

InterestController:

public function store(){

    //Get all the post values
    $inputs = Request::all();
    //From the post values get the array of interest ids that you are sending
    $interests = $inputs->interests;
    //For each interest id, save a new entry in the my_interest table
    foreach ($interests as $interest) {
        $interested_in = new MyInterests;
        $interested_in->user_id = Auth::id();
        $interested_in->interest_id = $interest;
        $interested_in->save();
            //dd($interests);
        }

    }

HTML:

{!! Form::open(array('id'=> 'form1')) !!}

                             @foreach($interests as $interest)

                                    <div class = "form-group">
                                        <div class="col-md-6">
                                            <div class="checkbox">
                                              <label><input type="checkbox" name = "interests[]" value="{{$interest->id}}">{{$interest->name}}</label>
                                            </div>
                                        </div>
                                    </div>
                            @endforeach

                                {!! Form:: submit('Sumbit', ['class' => 'btn btn-primary form-control']) !!}
                                {!! Form::close() !!}

3 个答案:

答案 0 :(得分:0)

您正在访问数组而不是收集。你的代码应该是。

$interests = $inputs['interests'];

答案 1 :(得分:0)

45行有错误,哪一行?我想要另外一个问题,你需要尝试这样的

Auth::user()->id;

答案 2 :(得分:0)

首先检查兴趣是否设置

if(isset($interests)){
    foreach ($interests as $interest) {
        $interested_in = new MyInterests;
        $interested_in->user_id = Auth::id();
        $interested_in->interest_id = $interest;
        $interested_in->save();
        //dd($interests);
    }
}