Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Laravel Relationship Events

chelout/laravel-relationship-events image

Laravel Relationship Events stats

Downloads
843.9K
Stars
484
Open Issues
8
Forks
32

View on GitHub →

Missing relationship events for Laravel

Laravel Relationship Events

Missing relationship events for Laravel

Build Status Total Downloads Latest Stable Version License

Install

  1. Install package with composer

Stable branch:

composer require chelout/laravel-relationship-events

Development branch:

composer require chelout/laravel-relationship-events:dev-master
  1. Use necessary trait in your model.

Available traits:

  • HasOneEvents
  • HasBelongsToEvents
  • HasManyEvents
  • HasBelongsToManyEvents
  • HasMorphOneEvents
  • HasMorphToEvents
  • HasMorphManyEvents
  • HasMorphToManyEvents
  • HasMorphedByManyEvents
 
use Chelout\RelationshipEvents\Concerns\HasOneEvents;
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
use HasOneEvents;
 
public static function boot()
{
parent::boot();
 
/**
* One To One Relationship Events
*/
static::hasOneSaved(function ($parent, $related) {
dump('hasOneSaved', $parent, $related);
});
 
static::hasOneUpdated(function ($parent, $related) {
dump('hasOneUpdated', $parent, $related);
});
}
 
}
 
use Chelout\RelationshipEvents\Concerns\HasMorphToManyEvents;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
use HasMorphToManyEvents;
 
public static function boot()
{
parent::boot();
 
/**
* Many To Many Polymorphic Relations Events.
*/
static::morphToManyAttached(function ($relation, $parent, $ids, $attributes) {
dump('morphToManyAttached', $relation, $parent, $ids, $attributes);
});
 
static::morphToManyDetached(function ($relation, $parent, $ids) {
dump('morphToManyDetached', $relation, $parent, $ids);
});
}
 
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
 
}
  1. Dispatchable relationship events. It is possible to fire event classes via $dispatchesEvents properties and adding HasDispatchableEvents trait:
 
use Chelout\RelationshipEvents\Concerns\HasOneEvents;
use Chelout\RelationshipEvents\Traits\HasDispatchableEvents;
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
use HasDispatchableEvents;
use HasOneEvents;
 
protected $dispatchesEvents = [
'hasOneSaved' => HasOneSaved::class,
];
 
}

Relationships

Observers

Starting from v0.4 it is possible to use relationship events in Laravel observers classes Usage is very simple. Let's take User and Profile classes from One To One Relations, add HasRelationshipObservables trait to User class. Define observer class:

namespace App\Observer;
 
class UserObserver
{
/**
* Handle the User "hasOneCreating" event.
*
* @param \App\Models\User $user
* @param \Illuminate\Database\Eloquent\Model $related
*
* @return void
*/
public function hasOneCreating(User $user, Model $related)
{
Log::info("Creating profile for user {$related->name}.");
}
 
/**
* Handle the User "hasOneCreated" event.
*
* @param \App\Models\User $user
* @param \Illuminate\Database\Eloquent\Model $related
*
* @return void
*/
public function hasOneCreated(User $user, Model $related)
{
Log::info("Profile for user {$related->name} has been created.");
}
}

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->profile()->create([
'phone' => '8-800-123-45-67',
'email' => 'user@example.com',
'address' => 'One Infinite Loop Cupertino, CA 95014',
]);
// ...

Todo

  • Tests, tests, tests
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.


Chelout Laravel Relationship Events Related Articles

Debugging production Laravel apps without losing your mind image

Debugging production Laravel apps without losing your mind

Read article
Making Laravel MongoDB Operations Idempotent: Safe Retries for Financial Transactions image

Making Laravel MongoDB Operations Idempotent: Safe Retries for Financial Transactions

Read article
Building Transaction-Safe Multi-Document Operations in Laravel image

Building Transaction-Safe Multi-Document Operations in Laravel

Read article
Detecting and Fixing Race Conditions in Laravel Applications image

Detecting and Fixing Race Conditions in Laravel Applications

Read article
Cache Concurrency Limiting in Laravel 12.53.0 image

Cache Concurrency Limiting in Laravel 12.53.0

Read article
Laravel Deadlock: Manage Technical Debt with Expiring Code Markers image

Laravel Deadlock: Manage Technical Debt with Expiring Code Markers

Read article
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Blastup logo

Blastup

Blastup provides social media enhancement services including buying Instagram likes, followers, and views, with features like instant delivery and a variety of packages to suit different needs.

Blastup
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Honeybadger logo

Honeybadger

Simple developer-focused application monitoring for Laravel. Error tracking, log management, uptime monitoring, status pages, and more!

Honeybadger
Tighten logo

Tighten

We help companies turn great ideas into amazing apps, products, and services.

Tighten
Securing Laravel logo

Securing Laravel

The essential security resource for Laravel devs, covering everything you need to keep your apps secure. Sign up to receive weekly security tips and monthly in depth articles, diving deep into security concepts you need to know!

Securing Laravel