Only until Jan 16th: coupon RESOLUTION25 for 40% off Yearly/Lifetime membership!

Read more here

Automatic Column Value When Creating Records

If you want to generate some DB column value when creating record, one of the ways is to 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:

class Country extends Model {
protected static function boot()
{
parent::boot();
 
Country::creating(function($model) {
$model->position = Country::max('position') + 1;
});
}
}

Another option is to create an Observer class, with creating() method inside it.

Like our articles?

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

Recent New Courses