I would like to make sure that I correctly used model events listeners in Laravel 5 and I didn't messed up nothing (listener vs handler?). My solution works fine, but I wonder if I developed according to concept and convention of Laravel 5.
Goal: Always set $issue->status_id on some value when model is saving.
In app\Providers\EventServiceProvider.php
<?php namespace App\Providers;
...
class EventServiceProvider extends ServiceProvider {
...
public function boot(DispatcherContract $events)
{
parent::boot($events);
Issue::saving('App\Handlers\Events\SetIssueStatus');
}
}
In app\Handlers\Events\SetIssueStatus.php
<?php namespace App\Handlers\Events;
...
class SetIssueStatus {
...
public function handle(Issue $issue)
{
if (something)
{
$issueStatus = IssueStatus::where(somethingElse)->firstOrFail();
}
else
{
$issueStatus = IssueStatus::where(somethingAnother)->firstOrFail();
}
// issue_status() is One-to-One relations with IssueType (belongsTo)
$issue->issue_status()->associate($issueStatus);
}
}
Thank you for your time.