Chris
Chris

Reputation: 4436

How to use a protected property in an Eloquent model without Laravel trying to save it to the database

In one of my models, I have an attribute named "slug". When the slug is changed, I need to record the original slug before updating it to the new one, so my model has a protected property "originalSlug". Before saving the model, I do something like this in my model:

protected $originalSlug;

public function customSave($newSlug){
   $this->originalSlug = $this->slug;
   $this->slug = $newSlug;
   return $this->save();
}

Then I have an event that does other tasks using that originalSlug after a successful save. The problem is Laravel is trying to save the originalSlug to the database though it isn't actually an attribute and doesn't have a database column. So it fails with the "Column not found" error.

What could I do to get Laravel to ignore that originalSlug property, or is there a better way I should be doing this?

Upvotes: 1

Views: 1904

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81157

  1. If you want Eloquent to ignore a property, it needs to be accessible to set, otherwise __set will be called and Eloquent will treat it as an attribute.

  2. You can alternatively use mutator for this.

So here's what you need:

public $originalSlug;

public function customSave($newSlug){
   $this->originalSlug = $this->slug;
   $this->slug = $newSlug;
   return $this->save();
}

or:

protected $originalSlug;

public function customSave($newSlug){
   $this->originalSlug = $this->slug;
   $this->slug = $newSlug;
   return $this->save();
}

public function setOriginalSlugAttribute($value)
{
   $this->originalSlug = $value;
}

Then Eloquent will not set an originalSlug attribute , so it won't be saved to the db.

You can do that with events, like suggested in the comments, and I would suggest this way too.

Upvotes: 1

Related Questions