2

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
  • In Laravel, you can take benefit of 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 into SQL Server CREATE TRIGGER sqlservertutorial.net/sql-server-triggers/… Commented Feb 17, 2020 at 4:57
  • Yes I got it. I have written a listener in app provider. It works fine. Commented Feb 17, 2020 at 5:26

2 Answers 2

3

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

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

Comments

0

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();
});

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.