Home > Tips & Tricks > Laravel Model boot() Method

Laravel Model boot() Method

In Laravel eloquent model has a magical method called the boot() method. You can override the default behavior.

Suppose you want to set up some field value at the moment of creating the model in Laravel then you can declare the field’s value in the boot() method.

class User extends Model {

	public static function boot() {

		parent::boot();

		static::updating(function($model) {

			// do somthing here

		});
	}

}

For example, if you want to generate the UUID field then use the following example code.

public static function boot() {

	parent::boot();

	self::creating(function ($model) {

		$model->uuid = (string)Uuid::generate();

	});

}

Also Read:
Laravel Eloquent Methods firstOrNew firstOrCreate updateOrCreate

Being Tricky 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment