How to update column value in laravel

LaravelLaravel 4Eloquent

Laravel Problem Overview


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

  • id
  • title
  • image
  • body

I want to update only "image" column value.

Here's my code:

public function delImage($path, $id) {
	$page = Page::find($id);
	$page->where('image', $path)->update(array('image' => 'asdasd'));
	\File::delete($path);
}

it throws me an error, that i am trying to use where() on a non-object. How can i correctly update my "image" column value?

Laravel Solutions


Solution 1 - Laravel

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.

Solution 2 - Laravel

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 :)

Solution 3 - Laravel

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();

Solution 4 - Laravel

Try this method short and clean :

Page::where('id', $id)
  ->update(['image' => $path]);

An example from Laravel doc

Flight::where('active', 1)
      ->where('destination', 'San Diego')
      ->update(['delayed' => 1]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexander KimView Question on Stackoverflow
Solution 1 - LaravelThe AlphaView Answer on Stackoverflow
Solution 2 - LaravelS. GuyView Answer on Stackoverflow
Solution 3 - LaravelCubiczxView Answer on Stackoverflow
Solution 4 - LaravelRachid LoukiliView Answer on Stackoverflow