Hooking Models

Estimated reading: 1 minute

Let’s say you’re developing a module/app that adds functionality to Akaunting. However, to keep Akaunting up-to-date, you don’t want to, and shouldn’t, change/hack the core files.

Eloquent fires several events, allowing you to hook into many points in a model’s lifecycle. You can listen to these events using the Observers feature of Eloquent. Let’s make an example for modules.

First of all, create and install a module.

Then add the following code into the boot method of your Service Provider.

use App\Models\Common\Item;

...

    public function boot()
    {
        Item::observe('Modules\MyBlog\Observers\Common\Item');
    }

...

Then create the observer file:

<?php

namespace Modules\MyBlog\Observers\Common;

use App\Abstracts\Observer;
use App\Models\Common\Item;
use Modules\MyBlog\Models\Post;

class Item extends Observer
{
    public function updated(Item $item): void
    {
        $post = Post::where('item_id', $item->id)->first();

        $post->opening_stock = $item->quantity;

        $post->update();
    }
}

That’s all you need to do to hook a model.

Share this Doc

Hooking Models

Or copy link

CONTENTS