osb/app/Traits/NextKey.php

40 lines
741 B
PHP
Raw Normal View History

2018-08-11 05:09:41 +00:00
<?php
/**
* Works out the next ID to use for an Eloquent Table.
*
* If we update records, we update the record_id table
2018-08-11 05:09:41 +00:00
*/
namespace App\Traits;
use App\Models\Module;
2018-08-11 05:09:41 +00:00
trait NextKey
{
public static function boot()
{
parent::boot();
static::creating(function($model)
{
$model->id = self::NextId();
});
static::saved(function($model)
{
if ($model->wasRecentlyCreated) {
if (! defined(get_class($model).'::RECORD_ID'))
throw new \Exception('Missing record_id const for '.get_class($model));
$mo = Module::where('name',$model::RECORD_ID)->firstOrFail();
$mo->record->id = $model->id;
$mo->record->save();
}
});
2018-08-11 05:09:41 +00:00
}
public static function NextId()
{
return (new self)->max('id')+1;
}
}