S
S
shasoft2018-12-26 20:14:39
Laravel
shasoft, 2018-12-26 20:14:39

Is it possible to make a global hook so that the where('mandt','=','120') condition is added to all queries in the database?

I want to add a separate mandt field to all tables in the database, in which there will be a site identifier and in order to determine for which site the data is selected from this field. Is it possible to somehow add a global hook so that the where('mandt','=','120') condition is added to all queries to the database?
ps yes, I know that separate databases are better for speed, but in this case the load is minimal and this is not critical.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin B., 2018-12-26
@shasoft

You have Model.php in the App folder, if not, then you need to create it, but in theory it is there and all your models should inherit
it. You need to write a global scope request in it

<?php
namespace App;

use Illuminate\Database\Eloquent\Model as Eloquent;

abstract class Model extends Eloquent
{
    public static function boot()
    {
        parent::boot();
        static::addGlobalScope('mandt', function (\Illuminate\Database\Eloquent\Builder $builder) {
            $builder->where('mandt', '=', '120');
        });
    }
}

V
Vitaliy Orlov, 2018-12-26
@orlov0562

You need to create your own class inheritor of the model and override the main methods in it, such as

class MyModel extends Illuminate\Database\Eloquent\Model {
    public function save(...){
        this->where(....);
        parent::save();
    }
}

add the necessary modifications inside the methods, then inherit all created models from the new class. I think the idea is clear - classic OOP.

S
shasoft, 2018-12-26
@shasoft

I just came up with the idea, by analogy with SoftDeletes, to do

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question