Skip to content

Instantly share code, notes, and snippets.

@hartmann-lars
Created February 27, 2018 23:52
Show Gist options
  • Save hartmann-lars/bcac638f2a5bbce0fd0ab34d86c74649 to your computer and use it in GitHub Desktop.
Save hartmann-lars/bcac638f2a5bbce0fd0ab34d86c74649 to your computer and use it in GitHub Desktop.
Laravel Observer skeleton file
<?php
namespace App\Observer;
use App\Models\MyModel;
class MyModelObserver
{
public function retrieved(MyModel $myModel)
{
//logic after the model has been retrieved
}
public function creating(MyModel $myModel)
{
//logic before the model is created
}
public function created(MyModel $myModel)
{
//logic after the model is created
}
public function updating(MyModel $myModel)
{
//logic before the model is updated
}
public function updated (MyModel $myModel)
{
//logic after the model is updated
}
public function saving(MyModel $myModel)
{
//logic before the model is saved
}
public function saved(MyModel $myModel)
{
//logic after the model is saved
}
public function deleting(MyModel $myModel)
{
//logic before the model is deleted
}
public function deleted(MyModel $myModel)
{
//logic after the model is deleted
}
public function restoring(MyModel $myModel)
{
//logic before the model is restored
}
public function restore(MyModel $myModel)
{
//logic after the model is restored
}
}
@hartmann-lars
Copy link
Author

hartmann-lars commented Feb 27, 2018

  1. Create the folder: App/Observers/, edit each Observer as you need and place them there.
  2. In Providers/AppServiceProvider, add each Observer you created in the boot method, like:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //Read it like: Your model::observes(YourModelObservers)
        \App\Models\MyModel::observe(\App\Observer\MyModelObserver::class);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment