提问者:小点点

如何将laravel复选框值插入数据库?错误:试图分配非对象的属性“record_id3”


我试图在laravel框架中插入复选框值到数据库中,但是不能。我总是犯错误。

这是我得到的错误:尝试分配非对象的属性'record_id3'

这是我在Controller中的代码:

    public function Postindex1(Request $request){        
    $pd4 = new Questioncourse();
    $pd4 = $request->all();
   
    $pd5 = implode(',', $request->input('hobby'));
    
    $pd5 = implode(',', $request->input('interest'));
    $pd5 = implode(',', $request->input('career'));
  
    $pd4['hobby'] = $pd5;
    $pd4['interest'] = $pd5;
    $pd4['career'] = $pd5;
    $pd4->record_id3 = Auth::user()->id;

    $pd4->save();

    return redirect('/question')->with('success', 'Your preferences have been saved!'); }

这是我在迁移中的代码:

 Schema::create('questioncourses', function (Blueprint $table) {
        $table->id();
        $table->integer('record_id3')->unsigned();
        $table->foreign('record_id3')->references('id')->on('users');
        $table->string('hobby');
        $table->string('interest');
        $table->string('career');
        $table->timestamps();

提前致谢


共1个答案

匿名用户

您的代码中存在一些错误:

$pd4 = new Questioncourse(); // Here you instanciate the Questioncourse Model
$pd4 = $request->all(); // Here you discard the value of $pd4 and change it with an Array 
                        // containing the $request data

因此,您不再有的实例,因此,您不能使用calss's方法或属性(如

你要做的是:

> all()/code>,请将其删除,

为每个复选框组使用不同的变量(不仅仅是

使用赋值器来设置模型属性的值,因此您的最终代码应该如下所示:

public function Postindex1(Request $request){
    $pd4 = new Questioncourse();
    // $pd4 = $request->all(); There is no need for this

    $hobby = implode(',', $request->input('hobby'));
    $interest = implode(',', $request->input('interest'));
    $career = implode(',', $request->input('career'));

    $pd4->hobby = $hobby;
    $pd4->interest = $interest;
    $pd4->career = $career;
    $pd4->record_id3 = Auth::user()->id;

    $pd4->save();

    return redirect('/question')->with('success', 'Your preferences have been saved!'); 
}