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';
}