1

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?

5
  • Why don't you just raise the event before you call the save? Commented Sep 15, 2014 at 11:50
  • I only want the event to fire if the model has been successfully saved. Commented Sep 15, 2014 at 12:07
  • 1
    Yea you can raise the event, pass the old data as a DTO. Then only fire it after the model has saved successfully. This series might help: laracasts.com/series/commands-and-domain-events Commented Sep 15, 2014 at 12:13
  • Thanks for the info. I'll look into that series. It's a bit over my head at the moment, but it might very well be the best way to do it. Commented Sep 15, 2014 at 17:43
  • Possible solution: stackoverflow.com/questions/22297240/… Commented Jun 26, 2015 at 22:14

1 Answer 1

1
  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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.