Hi,
I need to send an email to more than one user (admin and the user who created the model) every time a specific model is created.
To do this, I created this function inside the model:
public function sendMail( User $user)
{
$admin = new User;
$admin ->email = '[email protected]';
\Mail::to($user)->cc($admin)->send(new Welcome($user));
flash('Email sent.','success');
}
@vinschi I’m with @EventFellows: you’ll want to queue this. You don’t want to slow your application down because it needs to send emails every time a model’s created.
You could hook into the model’s created and queue your email there:
class Foo extends Model
{
public static function boot()
{
parent::boot();
static::created(function ($model) {
dispatch(new ModelCreated($model));
});
}
}
The job would then send the email when processed by a queue worker:
class ModelCreated implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $model;
public function __construct(Model $model)
{
$this->model = $model;
}
public function handle()
{
$admin = '[email protected]';
Mail::to($model->user)
->cc($admin)
->send(new ModelCreatedMail($model));
}
}