如何将数据从数据库传递到 Mailable?

How to pass data from database to Mailable?

我知道如何将数据传递给 view 但你如何将数据传递给 mailable?我也对将数据库调用 DB::selectcontrollermailable 放在哪里感到困惑?到目前为止我试过这个:

web.php:

Route::get('/test-email', 'App\Http\Controllers\TestMailController@test');

TestMailController.php:

<?php

namespace App\Http\Controllers;

use App\Mail\ContactMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class TestMailController extends Controller
{
    public function test()
    {
        return new ContactMail();
    }
}

TestMail.php:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;

class TestMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $data;

    public function __construct()
    {
        $this->data = DB::select('select * from db_name');
    }

    public function build()
    {
        return $this->markdown('emails.testmail')->with('data', $data);
    }
}

您需要使用 $this :

public function build()
{
    return $this->markdown('emails.testmail')->with('data', $this->data);
}