Skip to content

Laravel Eloquent Model 'getDirty()' behaviour #10735

@algorhythm

Description

@algorhythm

I'm not sure if this is a bug or a misunderstood behaviour. Following happens with using the 'isDirty()' and 'getDirty()' methods in the Eloquent Model class on setting floats:

I have a column 'netPrice' created with migrations:

Schema::table('invoices', function (Blueprint $table) {
    $table->float('net_price', 8, 4)->unsigned()->nullable();
});

Now I have a Model like this:

class Invoice extends Model {
    protected $table = 'invoices';
    protected $casts = ['net_price' => 'float'];
}

Suppose that the Model is filled with e.g. "24.9900" (string) and I fill it with 24.99 (float) then the method getDirty() shows me the column 'net_price'. OK, I understand, that a string is not a float, but the value written in DB is the same. So we do not have to write it to DB, nothing changes. When I call the property $price = $invoice->net_price I got 24.99 (float).

Question

Why is getDirty() not using my specified $casts to compare the values? Doesn't it make sense?

Workaround

I created a workaround in my code: When I fill the property 'net_price' I do it like this:

$invoice->net_price = number_format(24.99, 4); // "24.9900"

and then the Model isn't dirty anymore.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions