I have three tables: Products, Categories and a pivot one CategoryProduct.
I have an attribute updated_by and I want this to be automatically set to Auth::id() upon all create/update requests.
So far I am able to save data by using the sync() method ie.
$categoriesArray = [
1 => ['updated_by' => Auth::id()],
2 => ['updated_by' => Auth::id()],
...
];
$product->categories()->sync($categoriesArray);
I want to simplify the above by overriding the save method on CategoryProduct model ie.
class CategoryProduct extends Model
{
protected $table = 'category_product';
protected $fillable = ['product_id', 'category_id', 'created_by', 'updated_by'];
public function save(array $options = array())
{
$this->updated_by = $this->updated_by ?: Auth::id();
parent::save($options);
}
}
So that I can save my categories like so:
$categoriesArray = [1, 2, 3];
$product->categories()->sync($categoriesArray);
However for some reason the save method is not triggered upon saving resulting in a MySQL error.
General error: 1364 Field 'updated_by' doesn't have a default value.
Any ideas?