Automatic Column Value When Creating Records

If you want to generate some DB column value when creating record, add it to model's boot() method. For example, if you have a field "position" and want to assign the next available position to the new record (like Country::max('position') + 1), do this:

1class Country extends Model {
2 protected static function boot()
3 {
4 parent::boot();
5 
6 Country::creating(function($model) {
7 $model->position = Country::max('position') + 1;
8 });
9 }
10}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord