phplaravelmailtrap

How to send email notification in Laravel and MailTrap


I am trying to send an HTML template to MailTrap using this method

public function send($result_id)
    {

         $result = Result::whereHas('user', function ($query) {
                 $query->whereId(auth()->id());
             })->findOrFail($result_id);

        \Mail::to('test@eam.com')->send(new ResultMail);

        return view('client.result', compact('result'))->withStatus('Your test result has been sent successfully!');

    }

with the result.blade.file

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Test No. {{ $result->id }}</title>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
        <style type="text/css">
            html {
                margin: 0;
            }
            body {
                background-color: #FFFFFF;
                font-size: 10px;
                margin: 36pt;
            }
        </style>
    </head>
    <body>
        <p class="mt-5">Total points: {{ $result->total_points }} points</p>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Question Text</th>
                    <th>Points</th>
                </tr>
            </thead>
            <tbody>
                @foreach($result->questions as $question)
                    <tr>
                        <td>{{ $question->question_text }}</td>
                        <td>{{ $question->pivot->points }}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </body>
</html>

but I'm get an error

Undefined variable: result (View: C:\Users\USER\Documents\Laravel-Test-Result-PDF-master\Laravel-Test-Result-PDF-master\resources\views\client\result.blade.php)


Solution

  • Well, as far as I know, you need to have Mailable class and from the mailable class, you need to return the view and pass the data there. You'r mailable class should

    class ResultMail extends Mailable
    {
      use Queueable, SerializesModels;
    
      public $result;
    
      /**
       * Create a new message instance.
       *
       */
        public function __construct($result)
        {
            $this->result = $result;
        }
    
        /**
         * Build the message.
         *
         * @return $this
         */
        public function build()
        {
    
            return $this->view('client.result');
        }
    }
    

    Should be something like this.And then you need to pass the data to ResultMail

    \Mail::to('test@eam.com')->send(new ResultMail($result));