J
J
JohnDaniels2017-02-07 06:23:59
Laravel
JohnDaniels, 2017-02-07 06:23:59

How to update an entry in Laravel?

There is such a plate
51f7cd3d325e4e49ac14efd124b83ffa.png
Model:

class Result extends Eloquent
{
    protected $table = 'assets_to_users';
    protected $fillable = ['user_id', 'result'];

   public function asset()
   {
       return $this->hasOne('Application\Models\Asset', 'id', 'asset_id');
   }
}

And this code:
$asset_id = 2;

Result::updateOrCreate(
                ['asset_id' => $asset_id],
                ['result' => 100]
            );

After that, the plate takes the following form:
207d1606643b42a6ab4a9d6b2a611f91.png
While
$model = Result::where('asset_id', '=', $asset_id)->first();
echo $model->id; //122

Why is the wrong row being updated?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrzej Wielski, 2017-02-07
@wielski

You misunderstand the purpose of the updateOrCreate function.
In your case, you need to get an instance of the Result object, and then make changes to it.

$model = Result::where('asset_id', '=', $asset_id)->first();
$model->result = 100;
$model->save();

V
Vlad, 2017-02-07
@Result007

You have $fillable = ['user_id', 'result'] allowed to change or add user_id, and you are trying to access asset_id.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question