Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

elcuy's avatar
Level 2

Manual auto increment based on another field

Hey everyone!

I have a table which has three columns: id (primary key, auto incrementing), inner_id and process_id When I insert a new record on the table I need to set the inner_id based on the process_id, sort of like this:

Record ID 1 belongs to Process ID 1 and has an inner ID of 1
Record ID 2 belongs to Process ID 1 and has an inner ID of 2
Record ID 3 belongs to Process ID 1 and has an inner ID of 3
Record ID 4 belongs to Process ID 2 and has an inner ID of 1
Record ID 5 belongs to Process ID 1 and has an inner ID of 4
Record ID 6 belongs to Process ID 2 and has an inner ID of 2
Record ID 7 belongs to Process ID 2 and has an inner ID of 3
Record ID 8 belongs to Process ID 3 and has an inner ID of 1

So what i'm doing is a mutator in the table's model:

public function setInnerIdAttribute($value)
    {
        if(!$value || $value == 0){
            $this->attributes['inner_id'] = Instance::where('process_id', $this->attributes['process_id'])->max('inner_id') + 1;
        }
    }

On every record I create I get the number 0 on the inner_id field. I know this isn't the way to do it, but any help in this matter would be appreciated. What way is the cleanest? I also thought of creating a method called setInnerId, which I would call on each created object to set the value. Its very important that it ONLY works on inserts, since once its set the inner_id shouldn't be changed to another value.

0 likes
4 replies
elcuy's avatar
Level 2

Bumping this question. Is there really no way of doing it?

pmall's avatar
pmall
Best Answer
Level 56

Just use model observers, and calculate the ids on creating observer.

Here the setter doesn't work because... As this field is auto-generated, it never gets assigned to the object, so the mutator isn't fired.

nfauchelle's avatar

@elcuy I do something similar, and hook into the creating event so it's only done once at creation.

like this put in the Instance class

    public static function boot() {
        Instance::creating(function($model)
        {
            $model->inner_id = Instance::where('process_id', $model->process_id)->max('inner_id') + 1;
        });
    }
elcuy's avatar
Level 2

Although @nfauchelle 's answer is totally valid, I'm gonna select @pmall 's answer as the best one for my needs. I didn't know about model events or model observers, but in my case I think the observers will suit me best. Thank you both for your answers!

Please or to participate in this conversation.