PHPackages                             artificertech/laravel-relationship-events - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. artificertech/laravel-relationship-events

ActiveLibrary

artificertech/laravel-relationship-events
=========================================

Missing relationship events for Laravel

v0.2.1(3y ago)1218.8k1[2 issues](https://github.com/artificertech/laravel-relationship-events/issues)MITPHPPHP ^7.4|^8.0

Since Feb 9Pushed 3y ago1 watchersCompare

[ Source](https://github.com/artificertech/laravel-relationship-events)[ Packagist](https://packagist.org/packages/artificertech/laravel-relationship-events)[ Docs](https://github.com/artificertech/laravel-relationship-events)[ RSS](/packages/artificertech-laravel-relationship-events/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (3)Dependencies (6)Versions (6)Used By (0)

Laravel Relationship Events
===========================

[](#laravel-relationship-events)

Missing relationship events for Laravel

This package was intitally forked from  which is not being actively developed. This package is a different take on the original idea that allows relationship event listeners to be created on a per-relationship basis

This package is still in development. Feel free to contribute by submitting a pull request

 [![Build Status](https://github.com/artificertech/laravel-relationship-events/workflows/tests/badge.svg)](https://github.com/artificertech/laravel-relationship-events/actions) [![Total Downloads](https://camo.githubusercontent.com/8101bcaf64e840681dcbb36a7f189ff9709e0bfd9559a9885784584a61fed5b5/68747470733a2f2f706f7365722e707567782e6f72672f617274696669636572746563682f6c61726176656c2d72656c6174696f6e736869702d6576656e74732f642f746f74616c2e737667)](https://packagist.org/packages/artificertech/laravel-relationship-events) [![Latest Stable Version](https://camo.githubusercontent.com/789a51b521f77db8baf88e6ef2c9e072570b3ad27460ab3486e2503201e67429/68747470733a2f2f706f7365722e707567782e6f72672f617274696669636572746563682f6c61726176656c2d72656c6174696f6e736869702d6576656e74732f762f737461626c652e737667)](https://packagist.org/packages/artificertech/laravel-relationship-events) [![License](https://camo.githubusercontent.com/0d6dee2244b41b5670252635cae4b46767fda76a7c377b62072a05957b12e83c/68747470733a2f2f706f7365722e707567782e6f72672f617274696669636572746563682f6c61726176656c2d72656c6174696f6e736869702d6576656e74732f6c6963656e73652e737667)](https://packagist.org/packages/artificertech/laravel-relationship-events)

Install
-------

[](#install)

1. Install package with composer

#### Latest Release:

[](#latest-release)

Currently there are no releases for this project as it is still in development.

```
composer require artificertech/laravel-relationship-events

```

#### Development branch:

[](#development-branch)

```
composer require artificertech/laravel-relationship-events:dev-master

```

2. Add the HasRelationshipEvents trait to your model

```
use Artificertech\RelationshipEvents\Concerns\HasRelationshipEvents;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasRelationshipEvents;

    public static function boot()
    {
        parent::boot();

        /**
         * hasOne
         */
        static::hasOneSaved('profile', function ($user, $profile) {
            dump('hasOneSaved', $user, $profile);
        });
    }

    public function profile()
    {
        return $this->hasOne(Profile::class)->withEvents();
    }

}
```

For all saving, attaching, creating, etc events that are fired before the operation takes place you may return false from the event listener to cancel the operation

```
use Artificertech\RelationshipEvents\Concerns\HasRelationshipEvents;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasRelationshipEvents;

    public static function boot()
    {
        parent::boot();

        /**
         * hasMany
         */
        static::hasManyCreating('posts', function ($user, $post) {
            if ($post->name == 'badName') return false;
        });
    }

    public function posts()
    {
        return $this->hasMany(Post::class)->withEvents();
    }

}
```

3. Dispatchable relationship events. It is possible to fire event classes via $dispatchesEvents properties

```
use Artificertech\RelationshipEvents\Concerns\HasRelationshipEvents;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasRelationshipEvents;

    protected $dispatchesEvents = [
        'postsCreating' => UserPostsCreating::class,
        'postsCreated' => UserPostsCreated::class,
        'postsSaving' => UserPostsSaving::class,
        'postsSaved' => UserPostsSaved::class,
    ];

    public function posts()
    {
        return $this->hasMany(Post::class)->withEvents();
    }

}
```

Observers
---------

[](#observers)

It is possible to use relationship events in [Laravel observers classes](https://laravel.com/docs/eloquent#observers) Usage is very simple. Define observer class:

```
namespace App\Observer;

class UserObserver
{
    /**
     * Handle the User "postsCreating" event.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Post $post
     *
     * @return void
     */
    public function postsCreating(User $user, Post $post)
    {
        Log::info("Creating post: {$post->name} for user {$user->name}.");
    }

    /**
     * Handle the User "postsCreated" event.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Post $post
     *
     * @return void
     */
    public function postsCreated(User $user, Post $post)
    {
        Log::info("Post: {$post->name} for user: {$user->name} has been created.");
    }

    /**
     * Handle the User "postsCreating" event.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Post $post
     *
     * @return void
     */
    public function postsSaving(User $user, Post $post)
    {
        Log::info("Saving post: {$post->name} for user {$user->name}.");
    }

    /**
     * Handle the User "postsCreated" event.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Post $post
     *
     * @return void
     */
    public function postsSaved(User $user, Post $post)
    {
        Log::info("Post: {$post->name} for user: {$user->name} has been saved.");
    }
}
```

### Detecting observable events

[](#detecting-observable-events)

the laravel-relationship-events package cannot automatically detect relationship events that you want to observe. Please define them in your model class like so:

```
class User extends Model
{
    use HasRelationshipEvents;

    /**
     * User exposed observable events.
     *
     * These are extra user-defined events observers may subscribe to.
     *
     * @var array
     */
    protected $observables = [
        'postsCreating',
        'postsCreated',
        'postsSaving',
        'postsSaved',
    ];

    public function posts()
    {
        return $this->hasMany(Post::class)->withEvents();
    }

}
```

Don't forget to register an observer in the `boot` method of your `AppServiceProvider`:

```
namespace App\Providers;

use App\Models\User;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
// ...
    public function boot()
    {
        User::observe(UserObserver::class);
    }
// ...
}
```

And now just create profile for user:

```
// ...
$user = factory(User::class)->create([
    'name' => 'John Smith',
]);

// Create profile and assosiate it with user
// This will fire two events hasOneCreating, hasOneCreated
$user->post()->create([
    'name' => 'My first post!',
]);
// ...
```

Customizing the event name
--------------------------

[](#customizing-the-event-name)

By default the relationship event name is equal to the relationship function name with the action taking place in camel case. For example if you have a HasOne relationship "profile" then the event names would be "profileCreating", "profileCreated", "profileSaving", "profileSaved".

You may customize the event name by passing the relationship name into the withEvents() function as a string. For example:

```
class User extends Model
{
    use HasRelationshipEvents;

    public function posts()
    {
        return $this->hasMany(Post::class)->withEvents('userPost');
    }

}
```

will fire "userPostCreating", "userPostCreated", "userPostSaving", "userPostSaved" events

Relationship Specific info
--------------------------

[](#relationship-specific-info)

Each relationship as slightly different events. For example the belongsTo relationship fires {relationship}Associating, {relationship}Associated, {relationship}Dissociating, and {relationship}Dissociated events

- [Belongs To](doc/belongs-to.md)
- [Has Many](doc/has-many.md)
- [Has One](doc/has-one.md)
- [Morph Many](doc/morph-many.md)
- [Morph One](doc/morph-one.md)
- [Morph To](doc/morph-to.md)

Todo
----

[](#todo)

- Fix Automated Tests
- Add documentation for ManyToMany type events (these events can be handled by the built in pivot models and do not need this package)
- Non-Default event name tests
- Event Dispatcher Tests
- Event Listener Exception Tests
- HasOneThrough &amp; HasManyThrough
- New HasOneOfMany relationship?

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance17

Infrequent updates — may be unmaintained

Popularity28

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 72.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~206 days

Total

3

Last Release

1141d ago

PHP version history (2 changes)v0.1PHP ^7.2|^8.0

v0.2PHP ^7.4|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/26300af7b89f84f6a6b6ef2ffb592a3e5663b3d8ed7d65a6699a86aab65ed411?d=identicon)[cole.shirley](/maintainers/cole.shirley)

---

Top Contributors

[![chelout](https://avatars.githubusercontent.com/u/9196257?v=4)](https://github.com/chelout "chelout (148 commits)")[![coleshirley](https://avatars.githubusercontent.com/u/84236864?v=4)](https://github.com/coleshirley "coleshirley (30 commits)")[![saleem-hadad](https://avatars.githubusercontent.com/u/12780866?v=4)](https://github.com/saleem-hadad "saleem-hadad (19 commits)")[![nhedger](https://avatars.githubusercontent.com/u/649677?v=4)](https://github.com/nhedger "nhedger (2 commits)")[![titantwentyone](https://avatars.githubusercontent.com/u/1583366?v=4)](https://github.com/titantwentyone "titantwentyone (1 commits)")[![alvin-nt](https://avatars.githubusercontent.com/u/5227472?v=4)](https://github.com/alvin-nt "alvin-nt (1 commits)")[![waltoncon](https://avatars.githubusercontent.com/u/7566870?v=4)](https://github.com/waltoncon "waltoncon (1 commits)")[![giekus](https://avatars.githubusercontent.com/u/52037203?v=4)](https://github.com/giekus "giekus (1 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (1 commits)")[![rennokki](https://avatars.githubusercontent.com/u/21983456?v=4)](https://github.com/rennokki "rennokki (1 commits)")

---

Tags

laraveleventsrelationsrelationship

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/artificertech-laravel-relationship-events/health.svg)

```
[![Health](https://phpackages.com/badges/artificertech-laravel-relationship-events/health.svg)](https://phpackages.com/packages/artificertech-laravel-relationship-events)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[chelout/laravel-relationship-events

Missing relationship events for Laravel

5252.3M17](/packages/chelout-laravel-relationship-events)[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k43.5M5.2k](/packages/larastan-larastan)[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M532](/packages/laravel-passport)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
