douan7601 2016-01-04 11:15
浏览 57
已采纳

如何在Laravel中更新记录时将表单后期数据加载到模型中

I'm trying to update a record with the post data from a form. Every time I'm manually assigning the values from the form to the model and saving the record.

$model = CondoFacilities::find($id);

$model->facility_title = Input::get('facility_title');
$model->facility_description = Input::get('facility_description');
$model->facility_image = $imageName;

$status = $model->save();

Is there any way to assign the form data to the model and save/update the record in Laravel ? Similar to the one in YII2:

$model = $this->findModel($id);

if ($model->load(Yii::$app->request->post())) {
    $model->save();
}

I'm new to Laravel hope this awesome feature is available in Laravel as well.

Thank you for your help.

  • 写回答

1条回答 默认 最新

  • dongyan1936 2016-01-04 11:32
    关注

    In order to create a model and store it in the database, you can use create method directly on the model like so:

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

    where $request->all() is the post request of the form with the values that you wish to create and save it in the database.

    Similarly, for updating the model, you need to first find the model:

    $model = YourModel::find($id);
    

    where $id is the unsigend integer of the model that you wish to update.

    $model->update($request->all());
    

    Of course you can also inline the update method like so:

    YourModel::find($id)->update($request->all());
    

    Read more about Eloquent and Requests

    Hope this helps you out. Happy Coding. Cheers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案