How to update column value in laravel

后端 未结 3 1148
小鲜肉
小鲜肉 2020-12-23 19:49

I have a page model. It has following columns in database table:

  • id
  • title
  • image
  • body

I want to update only \"image\"

相关标签:
3条回答
  • 2020-12-23 20:16

    I tried to update a field with

    $table->update(['field' => 'val']);
    

    But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"

    Hope it will help someone :)

    0 讨论(0)
  • 2020-12-23 20:24

    You may try this:

    Page::where('id', $id)->update(array('image' => 'asdasd'));
    

    There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:

    $page = Page::find($id);
    
    // Make sure you've got the Page model
    if($page) {
        $page->image = 'imagepath';
        $page->save();
    }
    

    Also you may use:

    $page = Page::findOrFail($id);
    

    So, it'll throw an exception if the model with that id was not found.

    0 讨论(0)
  • 2020-12-23 20:34

    Version 1:

    // Update data of question values with $data from formulay
    $Q1 = Question::find($id);
    $Q1->fill($data);
    $Q1->push();
    

    Version 2:

    $Q1 = Question::find($id);
    $Q1->field = 'YOUR TEXT OR VALUE';
    $Q1->save();
    

    In case of answered question you can use them:

    $page = Page::find($id);
    $page2update = $page->where('image', $path);
    $page2update->image = 'IMGVALUE';
    $page2update->save();
    
    0 讨论(0)
提交回复
热议问题