Laravel - save vs update

Viewed 853

I am wondering which one is a better solution for updating a database record - addResources1 or addresources2?

First I tried the update query method since it looks clear to me. The second thought was, I was building models so lets use them and then just save.

What do you think?

There are several similar topics, however they say that save() will just insert a new record, in this case its not true.

ResourcesService:

 namespace App\Services;

 use App\Resource as Resource;
 use Illuminate\Support\Facades\Auth;

 class ResourcesService
 {

     public function addResources1($userId, $wood, $stone, $food, $gold)
     {
         $resources = new Resource;
         $resources = $resources->where('userId', $userId)->update([
         'wood' => $wood,
         'stone' => $stone,
         'food' => $food,
         'gold' => $gold,
          ]);
      }

      public function addResources2($userId, $wood, $stone, $food, $gold)
      {
          $resources = new Resource;
          $resources = $resources->where('userId', $userId)->first();
          $resources->wood = $wood;
          $resources->stone = $stone;
          $resources->food = $food;
          $resources->gold = $gold;
          $resources->save();
      }
}

Resource model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Resource extends Model
{
    protected $table = 'resources';

}
2 Answers

This depends on your use case.

1) What will have the least amount of SQL queries?

Method addResources1 will use 1 SQL query.

Method addResources2 will use 2 SQL queries. One for fetching the record and the other for updating the record.


2) Is the model sensitive? (e.g. is_admin bool column)

If it does have sensitive column, you should not have that column put in the fillable property of the model and thus method addResources1 will fail.


3) Do I need to do something else AFTER recording the updates but BEFORE committing to the database?

In this case, addResources2 will better suit you since it wouldn't commit unless save() is executed and that's after all your other business logic is completed.

Code Review is better site of Stackexchange network for this kind of questions. If you are confident about what you are doing, first sample is ok. I am saying that because second example is going to update just one row in database even in case there is more rows with same value of userId column. If you know your structure first sample is more clear for see what does it do. Also, if you set relations between models you could chain it in a way

$user->resources()->update(['wood' => $wood, 'stone' => $stone, 'food' => $food, 'gold' => $gold,]);
Related