1

I am using spatie/laravel-data to work with some data that eventually gets inserted into the database.

One of the things I need to do is sum up and average some things while I'm doing calculations, and I have (maybe unwisely) stored the running sum as a property (let's call it $myDataObject->runningTotal) on my Laravel-data model. Every other property can directly be mapped to a Database column.

At the end I've been doing a MyEloquentModel::insert($myDataCollection->toArray()); command, but now that I've added this runningTotal property, I get an error because Eloquent tries to insert to a column that doesn't exist.

I'd like to ignore that property altogether when transforming my laravel-data object to an Eloquent model, but I can't see anyway to do this.

Offlein
  • 665
  • 6
  • 22
  • I don't know the package but if they are acting like a Model in some way you could try to `makeHidden` that particular field on the Collection, but not sure how they are implementing their `toArray` ... in a regular Model you can make things hidden and they won't be part of the serialization – lagbox Jun 09 '23 at 21:26
  • https://spatie.be/docs/laravel-data/v3/as-a-resource/lazy-properties maybe that page will help? talks about including or excluding properties – lagbox Jun 09 '23 at 21:32

2 Answers2

0

You can define in your DTO a custom function which filters out runningTotal:

<?php

namespace App\Data;

use Spatie\LaravelData\Data;


class SomeData extends Data
{
    public function __construct(
        public string $someData,
        public int $runningTotal,
    ) {
    }

    public function someData(): array
    {
        return $this->except('runnigTotal')->toArray();
    }
}

Then you called as so:

MyEloquentModel::insert($myDataCollection->someData())
Shaya Ulman
  • 1,299
  • 1
  • 12
  • 24
0

You could just unset the attribute before submission with:

unset($myDataCollection->runningTotal);

It is not a Laravel way but this uses PHP's built in method.