I am new to laravel. I want to know is there any particular better option to use in the following case in laravel. For an example I have a table called product and another table called productlog. While a product is created / updated / deleted in those cases I have to insert a log in productlog table. I know, I can insert these data directly in the controller while these actions happening. Except this laravel has any better feature to use in this case?
2 Answers
You want to perform some action while your Eloquent model is processing. Laravel’s Eloquent provide a convenient way to add your own action while the model is completing or has completed some action.
This is the list of all of the events, eloquent model fired that we can hook into:
- retrieved : after a record has been retrieved.
- creating : before a record has been created.
- created : after a record has been created.
- updating : before a record is updated.
- updated : after a record has been updated.
- saving : before a record is saved (either created or updated).
- saved : after a record has been saved (either created or updated).
- deleting : before a record is deleted or soft-deleted.
- deleted : after a record has been deleted or soft-deleted.
- restoring : before a soft-deleted record is going to be restored.
- restored : after a soft-deleted record has been restored.
For more details check the Laravel documentation here. Observers/ Model Events
Comments
I added this in my
app\Providers\AppServiceProvider.php
Product::created(function ($model) {
$producthistory = new Producthistory();
$producthistory >product_id = $model->id;
$producthistory >action = ' Product Created';
$producthistory >log = "Product created bla bla bla";
$producthistory >action_by = Auth::id();
$producthistory >save();
});
Event & Listeners, where a product is created/updated/deleted event is triggered then in the listeners will create/insert it's logs. Outside of Laravel, you can have a look intoSQL Server CREATE TRIGGERsqlservertutorial.net/sql-server-triggers/…