Support the ongoing development of Laravel.io →
Database Eloquent

i am trying to create an model event to track amendments..

the table structure uses a sequence field that 0 = current and evey other version has sequence incremented like so

id sequence value
1 0 £100 <-current record
2 3 £90
3 2 £101
4 1 £80

this is simple ish but i hit a an error that the event fires its self so how do i stop that.. or how do i divert the save to a create new and set old row sequance+1...

model event code

    static::updated(function($ledger){
	
		$changed = false;
		//has data changed... but ignore date fields
		foreach($ledger->getDirty() as $attribute => $value){
			if ($attribute != 'created_at' && $attribute != 'updated_at' && $attribute != 'deleted_at'){
				if($ledger->getOriginal($attribute) != $value){
					$changed = true;
					}
				}
			}
		if ($changed == true){
			$sequence = \Ledger::where('number','=',$ledger->number)->max('sequence') + 1;
			echo "sequence '$sequence'<br/>\r\n";
			$history = \Ledger::where('number','=',$ledger->number)
								->where(\DB::raw('DATE(updated_at)'),'=',\DB::raw('DATE(NOW())'))
								->first();
			if (!$history){ //if history dose not exisit for today create it
				$history  = new \Ledger
				}
			$history->sequence = $sequence;
			$history->val = $ledger->val;
			$history->save();
			}
		}

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.