Skip to content
Advertisement

Configuration observer in Laravel

I am beginner in Laravel. I use in my project Laravel 8.

I have this code:

  1. Controller
    public function index(Request $request)
        {
            $query = $this->model
                ->orderBy($request->column ?? 'created_at', $request->order ?? 'desc');
    
            if ($request->search) {
                $query->where(function ($query) use ($request) {
                    $query->where('name', 'like', '%' . $request->search . '%')
                        ->orWhere('id', 'like', '%' . $request->search . '%');
                });
            }
            return DictionaryResource::collection($query->paginate($request->per_page));
        }
    
        public function create()
        {
            $statuses = DB::table('status')->select('status.name as label', 'status.id as value')->get();
            $types = DB::table('dictionary_types')->select('dictionary_types.name as label', 'dictionary_types.id as value')->get();
            return response()->json([$statuses, $types]);
        }
    
        public function store(DictionaryRequest $request)
        {
            $data = $request->only([
                'name',
            ]);
    
            if($request->status == 2) $status = 2;
            else $status = 1;
    
            if(is_null($request->type)) $type = 1;
            else $type = $request->type;
    
            $data['status'] = $status;
            $data['type'] = $type;
    
            $this->model->create($data);
    
            return response()->json(['status' => 'success']);
        }

  1. Model
    class Dictionary extends Model
    {
        use ScopeActiveTrait,
            SoftDeletes;
    
        protected $guarded = ['id'];
    
        protected $fillable = [
            'name',
            'type',
            'status'
        ];
    
        protected $dates = [
            'deleted_at',
            'created_at',
            'updated_at'
        ];
    }

  1. Observer
    class DictionaryObserver
    {
    
        public function created(Dictionary $dictionary)
        {
            Log::info('yyyyyyyyy');
        }
    
        public function retrieved(Dictionary $dictionary)
        {
            Log::info('xxxxxxxxxx'.$dictionary);
        }
    
        public function updated(Dictionary $dictionary)
        {
            //
        }
    
        public function deleted(Dictionary $dictionary)
        {
            //
        }
    }

  1. ServiceProvider
    public function boot()
        {
            Paginator::useBootstrap();
            Dictionary::observe(DictionaryObserver::class);
        }

I have 2 questions / problems:

  1. How can I disable following in the controller (index method)? I only need to record the moment when someone opens one record for editing, and does not list all the records in the list

  2. I have model Action:

class Action extends Model
{
    use ScopeActiveTrait,
        SoftDeletes;

    protected $guarded = ['id'];

    protected $fillable = [
        'company_id',
        'user_id',
        'ip',
        'user_agent',
        'description'
    ];

    protected $dates = [
        'deleted_at',
        'created_at',
        'updated_at'
    ];
}

I need save to this model information about user ip, user_agent itp (user is logged). How can I make it?

Advertisement

Answer

As you’ve found, the “retrieved” method on the observer is called when you load the model instance, whether you load one or many (if you load many, it is called once for each model loaded).

You can suppress events being fired (and, having tested it, this includes both Events and Observers) by wrapping it in a callback function using the ::withoutEvents() static method.

So (using code from one of my sites) if I use :

$games = Game::where('id', '>=', 4900)->where('id', '<=', 4910)->get();

then the GameObserver will be called 11 times (because there are 11 models which are loaded). But if I wrap it in the ::withoutEvents method like so :

$games = Game::withoutEvents(function () {
    $games = Game::where('id', '>=', 4900)->where('id', '<=', 4910)->get();
return $games;
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement