Saurabh Parekh
Saurabh Parekh

Reputation: 449

Laravel Update not working

I have table called admins and model called Admin.

When i try to update the records it fails every time with one field.

$admindetail = Admin::find($id);
$admindetail->fill(['is_delete'=>1])->save();

Above code is not updating record in DB. datatype for is_delete is tinyint.

If i update name field it works with the same code like

$admindetail = Admin::find($id);
$admindetail->fill(['name'=>'abc'])->save();

Can you help me why first code is not working.

Upvotes: 9

Views: 31869

Answers (6)

UrbanwarfareStudios
UrbanwarfareStudios

Reputation: 360

Just a warning and this might seem obvious, but I just had this experience so I am sharing it so others save time!

Lets say your running this:

$skus = Model::select('ORDERDATE', 'ITEMSKU', 'COLOUR', 'SIZE','QTY')->where("price", "=", 10)->get();

If your primary key isn't in the select - you cannot loop through the resulting collection and update the models using save or update.

    foreach($skus AS $key => $sku){ 
      $sku->update(['price' => '12']); 
    }

It doesn't error and will carry on like it has worked but if you check the database it won't have updated, even if the columns you're updating are in your fillable.

Upvotes: 0

Akbarali
Akbarali

Reputation: 904

The update didn't work at all for me either. Then I found out that I called the transaction above and it didn't work because I returned without committing before returning.

Upvotes: 0

sathish R
sathish R

Reputation: 432

Instead of passing value as array, you could try the code below:

$admindetail = Admin::find($id);
if(!$admindetail)
{
  $admindetail->is_delete=1;
   $admindetail->save();
}

Upvotes: 2

Ramzan Mahmood
Ramzan Mahmood

Reputation: 1901

Model use to interact with table so all attributes which you need to store in DB you should need to define in your model as your Admin model should look like

   <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $fillable = ['name', 'is_delete'];
}

You missing is_delete from your Model code.

Upvotes: 23

Gilbert Tuazon
Gilbert Tuazon

Reputation: 11

You should check your fillable in your model like this:

protected $fillable = [
    'name',
    'is_delete'
];

Upvotes: 1

Andrii Lutskevych
Andrii Lutskevych

Reputation: 1389

Use boolean type, no integer 1: $adminDetail->fill(['is_delete' => true])->save();

And you can use as property without fill method and you do not need accept is_delete in the $fillable array:

$adminDetail->is_delete = true;
$adminDetail->save();

Upvotes: 1

Related Questions