# Defining Observers

You can listen for events on a given model by creating an observer class.

Observers are automatically registered by passing the model the observer is associated with.

php tea make:observer name=ProductObserver model=Product

<?php

namespace App\Http\Observers;

use App\Product;

class ProductObserver
{
    public function creating(Product $product): void
    {
    }

    public function created(Product $product): void
    {
    }

    public function updating(Product $product): void
    {
    }

    public function updated(Product $product): void
    {
    }

    public function deleting(Product $product): void
    {
    }

    public function deleted(Product $product): void
    {
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

Suppose you want to set a slug before creating a product, you can make use of the creating event:

public function creating(Product $product): void
{
    $product->slug = strtolower(str_replace(' ', '-', $product->title));
}
1
2
3
4

You can delete any unused event to clear the class.