mercredi 22 septembre 2021

How to pass data from background schedule job to global scope?

I have a background schedule job that doing some code and executing quires that have global scope append to their model and i'm trying to pass data from the job to the global scope like this

job.php

class Job
{

    public static function execute() {

        //Im trying here to find a cleaner and working way better than app()->user_id
        //even it's a bad way, it's also not working
        //because when trying to get the value in UserScope it's always null 
        app()->user_id  = 1;

        app(CreateObjectAction::class)->execute($data);
    }
}   

CreateObjectAction.php

class CreateObjectAction
{

    public function execute(Data $data)
    {
        try {

            DB::beginTransaction();
            
            if (app()->runningInConsole()) {

               //here app()->user_id always is null when the global scope `UserScope` is applied to the query
               //so $exist will be also always empty
               $exist = Object::query()->first();

            } else {
                //....
            }
            
            if(empty($exist)) {

                //here is trying to create an existed object and it gives error
                $object = Object::create(data)->toArray());

            }

            DB::commit();

            return $object;

        } catch (\Throwable $e) {
            DB::rollBack();
            Log::error($e->getTraceAsString());
            return null;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getTraceAsString());
            return null;
        }
    }
} 

Object.php

class Object extends Model
{
    use BelongsToUser;
}

BelongsToUser.php

trait BelongsToUser
{
    protected static function BelongsToUser()
    {

        static::addGlobalScope(new UserScope);

    }
}

UserScope.php

class UserScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        if (app()->runningInConsole()) {

                //here app()->user_id always null as well.
                $builder->where("{$model->getTable()}.user_id", "=", app()->user_id); 

        } else {
            //....
        }
    }
}

so please what is the best way that i can pass data from a job running by background worker in console to global scope may thanks in advance for any help



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire