Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phayes0289's avatar

Where to Register an Observer?

I am using Laravel 9 and need to register an "Observer". This is my observer:

<?php

namespace App\Observers;

use App\Models\Post;
use Illuminate\Support\Facades\Auth;

class PostObserver
{
    public function creating(Post $post)
    {
        $post->created_by = Auth::id();
    }

    public function updating(Post $post)
    {
        $post->updated_by = Auth::id();
    }
}

This is the related code in my model:

public function createdBy()
{
    return $this->belongsTo(User::class, 'created_by');
}

public function updatedBy()
{
    return $this->belongsTo(User::class, 'updated_by');
}

I believe I need to add the observer to EventService Provider, maybe?

protected $observers = [
    Post::class => PostObserver::class,
];

What is the proper code I need and where should it gp?

0 likes
5 replies
martinbean's avatar

@phayes0289 https://laravel.com/docs/9.x/eloquent#observers:

To register an observer, you need to call the observe method on the model you wish to observe. You may register observers in the boot method of your application's App\Providers\EventServiceProvider service provider

Alternatively, you may list your observers within an $observers property of your applications' App\Providers\EventServiceProvider class

kokoshneta's avatar

@martinbean The code given in the question matches the second of these options – except that the observer(s) should be enclosed in an array:

protected $observers = [
	Post::class => [PostObserver::class],
];
1 like
kokoshneta's avatar

@martinbean Ah, you’re right, it does an Arr::wrap() on it first. Then the code given in the question should be perfectly fine as is.

Please or to participate in this conversation.