人気のPHP WEBアプリケーションフレームワークLaravelのTipsを記録していきます

Laravel で エラー(Exception)発生時に管理者へメール通知する

● Laravel で エラー(Exception)発生時に管理者へメール通知する

・LaravelアプリケーションでエクセプションがThrowされたときに、Adminモデルの管理者宛にメールを通知してみます

● 1. Adminモデルに Notifiable トレイトを追加

/app/Admin.php

class Admin extends Authenticatable
{
    use \Illuminate\Notifications\Notifiable;

● 2. Notification ExceptionEmail を作成する

ExceptionEmail の名前は適宜変更可能です

php artisan make:notification ExceptionEmail

app/Notifications/ExceptionEmail.php が自動生成されます

エラー内容 Exception を受け取れるようにメンバ変数を設定します。
コンストラクタのタイミングでエラー内容を受け取ります

    private $ex;

    public function __construct( \Exception $ex )
    {
        $this->ex = $ex;
    }

また toEmail() メソッドを次のように修正します

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->greeting('ERRORが発生しています')
            ->line( \Request::fullUrl() )
            ->line( 'Exceptionクラス名 (' . get_class($this->ex) .')' )
            ->line( "{$this->ex->getFile()}:{$this->ex->getLine()}" )
            ->line( "{$this->ex->getMessage()}");
    }

● 3. Exception発生時にフックをかけて通知処理を間に挟む

app/Exceptions/Handler.php

    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

  ↓ このメソッドに管理者へメール通知する命令を追記します。(この例ではIDが1の管理者へメールを送信しています)

    public function report(Throwable $exception)
    {
        // 管理者にメール通知する
        $admin = \App\Admin::where('id','=',1)->first();
        // AuthenticationException|AuthorizationException|HttpException|ModelNotFoundException|ValidationException 以外の場合は 通知する
        if ( ! preg_match("/(AuthenticationException|AuthorizationException|HttpException|ModelNotFoundException|ValidationException)/", get_class($exception)) ){
            $admin->notify(new \App\Notifications\ExceptionEmail($exception));
        }
        // 管理者にメール通知する

        parent::report($exception);
    }

正規表現で次の Exception クラスの場合はメールを送信しないようにしています

\Illuminate\Auth\AuthenticationException
\Illuminate\Auth\Access\AuthorizationException
\Symfony\Component\HttpKernel\Exception\HttpException
\Illuminate\Database\Eloquent\ModelNotFoundException
\Illuminate\Validation\ValidationException

以上です。
とても簡単ですね。
これでエラーが発生すると管理者宛にこのようなメールが到着します

添付ファイル1
No.2016
10/29 10:12

edit

添付ファイル