mercredi 23 janvier 2019

Laravel 5.6 custom id with mutator reset counter everyday

I use a mutator to create a custom id for my records to make it look like this:

yyyy-mm-dd-{sequence}

The sequence looks like this

00001
00002
...

So it's 5 digits and is just a counter.

I have 2 problems

1) I don't know how to create a counter in my mutator, I can do a for loop but I don't now how to make an infinte loop that resets when it's tomorrow.

2) I honestly have no idea how to make it reset every day.

My mutator:

public function setFunctionalIdAttribute($id)
{
    $date = Carbon::now()->format("Y-m-d");

    // I take an extremely large number here because there will never be so much records in 1 day.
    for ($counter = 0; $counter <= 100000000000; $counter++) {
        $counter = str_pad($counter, 5, '0', STR_PAD_LEFT);
    }

    $today = Carbon::today();
    $tomorrow = Carbon::tomorrow();

    if ($today = $tomorrow) {
        $counter = 0;
    }

    $this->attributes['functional_id'] = $date . "-" . $counter;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire