[英]Automatically insert a data to database in certain cases in laravel
I am new to laravel.我是laravel的新手。 I want to know is there any particular better option to use in the following case in laravel.我想知道在 laravel 的以下情况下是否有更好的选择。 For an example I have a table called product and another table called productlog.例如,我有一个名为 product 的表和另一个名为 productlog 的表。 While a product is created / updated / deleted in those cases I have to insert a log in productlog table.在这些情况下创建/更新/删除产品时,我必须在 productlog 表中插入日志。 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?除了这个 Laravel 在这种情况下有什么更好的功能可以使用?
You want to perform some action while your Eloquent model is processing.您想在 Eloquent 模型正在处理时执行一些操作。 Laravel's Eloquent provide a convenient way to add your own action while the model is completing or has completed some action. Laravel 的 Eloquent 提供了一种方便的方法,可以在模型完成或已完成某些操作时添加您自己的操作。
This is the list of all of the events, eloquent model fired that we can hook into:这是所有事件的列表,我们可以连接到的 eloquent 模型:
For more details check the Laravel documentation here.有关更多详细信息,请在此处查看 Laravel 文档。 Observers/ Model Events观察者/模型事件
I added this in my我在我的
app\\Providers\\AppServiceProvider.php 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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.