Never Update the Column

If you have DB column which you want to be set only once and never updated again, you can set that restriction on Eloquent Model, with a mutator:

  • In version 9 and above:
1use Illuminate\Database\Eloquent\Casts\Attribute;
2 
3class User extends Model
4{
5 protected function email(): Attribute
6 {
7 return Attribute::make(
8 set: fn ($value, $attributes) => $attributes['email'] ?? $value,
9 );
10 }
11}
  • In version 9 and below:
1class User extends Model
2{
3 public function setEmailAttribute($value)
4 {
5 if (isset($this->attributes['email']) && ! is_null($this->attributes['email'])) {
6 return;
7 }
8 $this->attributes['email'] = $value;
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