R
R
Roman Olegovich2021-08-02 13:02:14
Laravel
Roman Olegovich, 2021-08-02 13:02:14

How to intercept and modify a request to the database before it is executed?

There is a task to intercept and add a comment to any SQL request.
I didn't find anything in the documentation other than ModelObserver and DB::listen ...
ModelObserver is not suitable, because it will only track requests from models.
DB::listen after its execution.

I would like something like this:

DB::beforeExecute(function($query){
    return $query . " -- некоторый комментарий к запросу"
})


are there any options?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene, 2021-08-02
@Nc_Soft

This can be done quickly by modifying the framework's sources in the vendor/laravel/framework/src/Illuminate/Database/Connection.php
file and modifying the run method (line 620)

protected function run($query, $bindings, Closure $callback)
    {
         $query.= '-- this is test comment';
        // остальной код

After that, a comment will cling to all requests.
To do this correctly, you need to go to config.app and write a custom provider that will replace
Illuminate\Database\DatabaseServiceProvider::class
and deal with db.factory and other Laravel drochev, but I'm just too lazy to do it, I just pointed out where to dig.

A
Alexander Aksentiev, 2021-08-02
@Sanasol

https://laravel.com/docs/master/eloquent#query-scopes

I
inFureal, 2021-08-19
@inFureal

It is possible through observers or events in the model itself. The joke is that nowhere (like) it says what events are.
Suppose make:observer creates created, updated, deleted, but there are others.
For example you can do

class ProductObserver {
    function saving(Product $product) {} // будет выполняться после каждого вызова save и ДО запроса в базу
    function saved(Product $product) {} // будет выполняться после вызова save и ПОСЛЕ запроса в базу
}

// В провайдере
Product::observe(ProductObserver::class);

или внутри модели
<code lang="php">
class Product extends Model {
    // ...
    static function boot() {
        parent::boot();
        static::saving(function(Product $product) {}); // то же самое что и выше пример
    }
    // ....
}
</code>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question