获取表的ID并插入其他列作为外键

时间:2019-07-10 09:20:45

标签: laravel eloquent laravel-5.8

他试图获取表的ID并作为外键插入到另一列中,但是它没有保存到db中并且没有显示任何错误

刀片文件:

  <form method="post" action="{{ route('day.store' , $form->id) }}">
              @csrf
            <button type="submit" id="save" class="btn btn-primary">Add this DataTime</button>
            <b><span id="showdatetime"></span></b>
            </form>

路线:

   Route::post('/form/day', 'DayController@store')->name('day.store');

控制器:

  public function store(Request $request)
  {
    Day::Create([
        'form_id' => $form_id,
        'selecteddatetime' => $date,

    ]);

    return back();

  }

型号:

  protected $guarded = [];

  public function form()
  {
        return $this->belongsTo('App\Form');
  }

1 个答案:

答案 0 :(得分:0)

您在路由中传递参数,但是您在存储方法中不接受此参数,因此请更改此参数

public function store(Request $request)
  {
    Day::Create([
        'form_id' => $form_id,
        'selecteddatetime' => $date,

    ]);

    return back();

  }

 public function store(Request $request, $form)
  {
    Day::Create([
        'form_id' => $form_id,
        'selecteddatetime' => $date,

    ]);

    return back();

  }

在模型中添加以下代码

 protected $fillable = ['form_id', 'selecteddatetime'];

 protected $guarded = ['id','form_id'];

  public function form()
  {
        return $this->belongsTo('App\Form');
  }

希望有帮助。

谢谢