Is it possible to ignore a laravel-data object property when converting to a model?

381 Views Asked by At

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.

2

There are 2 best solutions below

0
Shaya Ulman On

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())
0
Andrew Nelson On

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.