使用 Laravel 事件记录 table 创建

Log table creation using Laravel Events

我想在每次 files table 发生插入时创建一个日志。也就是说,每次插入 files table 时,都会触发一个事件以自动为其创建日志。 Log table 需要有 3 列 id, fileid - 文件 table & logDetails 的主键,其中 logDetails列存储类似 1 file inserted.

的消息

我已经阅读了这篇文章 - https://laravel.com/docs/8.x/events 并且还搜索了更多内容,但这无法帮助我找到我应该从哪里开始。我为此创建了一个事件页面和一个侦听器页面。但是我不知道在下面的 that.The 中写什么 Controller & model 可以很好地插入 files table。我需要你帮助的地方是编写代码来为这次插入创建一个日志。非常感谢任何帮助。

控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\FileLogs;
use Illuminate\Support\Facades\Validator;
use App\Events\InsertFileLog;

class FileLogController extends Controller
{
    public function insert(Request $request) // insertion
    {
        $validator = Validator::make(
            $request->all(),
            [
                
                'orderId'    => 'required|integer', //id of orders table
                'fileId'    => 'required|integer',  //id of file_type table
                'status'    => 'required|string'
            ]
        );

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        $obj = new FileLogs();
        $obj->orderId=$request->orderId;
        $obj->fileId=$request->fileId;
        $obj->status=$request->status;
        $obj->save();
        //dd($obj->id);
        if($obj->id!=''){
            InsertFileLog::dispatch($order);
            return response()->json(['status'=>'success','StatusCode'=> 200, 'message'=>'Successfully Inserted','data'=>$obj]);
        }
        
        else{
            return response()->json(['status'=>'Failed','message'=>'Insertion Failed'],400);
        }
        
    }

型号

class FileLogs extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $table='files';
    protected $fillable = [
        'orderId',
        'fileId',
        'status'
        
    ];
}

事件

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Models\FileLogs;

class InsertFileLog
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $order;
   
    public function __construct(FileLogs $order)
    {
        $this->order = $order;
    }
}

监听器

<?php

namespace App\Listeners;

use App\Events\InsertFileLog;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\Logs;

class FileLogListener
{
    public function __construct()
    {
        //
    }
    public function handle(InsertFileLog $event)
    {
        //
    }
}

EventServiceProvider.php

class EventServiceProvider extends ServiceProvider
{
    
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    public function boot()
    {
        //
    } 
} 

App\Providers\EventServiceProvider 提供了一种方法 register Events and Listeners。键是Event,值是一个或多个Listeners。您应该更新您的代码以包含以下内容:

EventServiceProvider

class EventServiceProvider extends ServiceProvider
{

    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        InsertFileLog::class => [
            // Listeners in this array will be executed when InsertFileLog was fired.
            FileLogListener::class
        ],
    ];


    public function boot()
    {
        //
    } 
} 

FileLogListener 只会在事件 InsertFileLog 触发后触发。为此,您可以执行以下操作,方法是在 insert 函数中的 return 成功响应之前添加 InsertFileLog::dispatch($order); 行。

文件日志控制器

class FileLogController extends Controller
{
    public function insert(Request $request) // insertion
    {
        $validator = Validator::make(
            $request->all(),
            [
                
                'orderId'    => 'required|integer', //id of orders table
                'fileId'    => 'required|integer',  //id of file_type table
                'status'    => 'required|string'
            ]
        );

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        $obj = new FileLogs();
        $obj->orderId=$request->orderId;
        $obj->fileId=$request->fileId;
        $obj->status=$request->status;
        $obj->save();
        //dd($obj->id);
        if($obj->id!=''){
            InsertFileLog::dispatch($obj);
            // alternatively, the event helper can be used.
            // event(new InsertFileLog($obj)); 
            return response()->json(['status'=>'success','StatusCode'=> 200, 'message'=>'Successfully Inserted','data'=>$obj]);
        }
        
        else{
            return response()->json(['status'=>'Failed','message'=>'Insertion Failed'],400);
        }
    }
}

FileLogListener

<?php

namespace App\Listeners;

use App\Events\InsertFileLog;
use App\Models\Log;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class FileLogListener
{
    public function __construct()
    {
        //
    }

    
    public function handle(InsertFileLog $event)
    {
        // $event->order contains the order.
        // In your question, you have request an example of creating an insertion to the Log table
        Log::create([
            'fileId' => $event->order->fileId,
            'logDetails' => '1 file inserted',
        ]);
    }
}

模型观察者

或者,Model observers 提供无需手动注册 events/listeners 的解决方案,因为他们会收听观察模型的 Eloquent events,例如:creatingcreatedupdateddeleted