Documentation: https://laravel.com/docs/5.8/events
Laracasts: https://laracasts.com/series/laravel-from-scratch-2018/episodes/32
php artisan make:event ProjectCreated
php artisan make:listener SendProjectCreatedNotification --event=ProjectCreated
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
class ProjectCreated
{
use Dispatchable, SerializesModels;
public $project; // $event->project
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($project)
{
$this->project = $project;
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Events\ProjectCreated;
use App\Project;
class ProjectsController extends Controller
{
// ...
// ...
public function store() {
$attributes = $this->validateProject();
$attributes['owner_id'] = auth()->id();
$project = Project::updateOrCreate($attributes);
event(new ProjectCreated($project));
return redirect('/projects');
}
// ...
}
<?php
namespace App\Listeners;
use App\Events\ProjectCreated;
use Illuminate\Support\Facades\Mail;
use App\Mail\ProjectCreated as ProjectCreatedMail; // use 'as' to prevent duplicate name
class SendProjectCreatedNotification
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param ProjectCreated $event
* @return void
*/
public function handle(ProjectCreated $event)
{
Mail::to($event->project->owner->email)->send(
new ProjectCreatedMail($event->project)
);
}
}
<?php
// ...
// ...
use App\Events\ProjectCreated;
use App\Listeners\SendProjectCreatedNotification;
class EventServiceProvider extends ServiceProvider
{
// ...
// ...
protected $listen = [
Registered::class => [
// ...
],
ProjectCreated::class => [
SendProjectCreatedNotification::class
]
];
// ...
}
<?php
namespace App;
use App\Events\ProjectCreated;
// ...
class Project extends Model
{
// ...
protected $dispatchesEvents = [
'created' => ProjectCreated::class
];
// ...
// ...
}