发送随机 ID - Laravel 电子邮件

sending random ids - Laravel email

美好的一天

提交表单后,我正在使用 Mailgun 向用户发送包含订单所需信息的电子邮件,我设法发送了主题和电子邮件地址,但我无法发送随机数在创建订单时分配。

这是我的控制器:

public function store(Request $request)
{
    $order = $user->orders()->create([

            'randomid' => rand(100000,999999),
            'subject' => $request->get('subject'),
            'email' => $request->get('email'),
    ]);

    $data = $request->only('subject', 'email', 'randomid');

    Mail::send('emails.note',
        $data
        , function($message) use ($data)
        {
            $message->subject('New Order: '.$data['subject'])
                ->from('myemail@myserver.com')
                ->to($data['email']);
        });
}

randomid 不是来自请求。您使用 rand(100000,999999) 手动生成它的值!

请试试这个:

public function store(Request $request){
    $data = [
        'randomid' => rand(100000, 999999) , 
        'subject' => $request->input('subject') , 
        'email' => $request->input('email')
    ];
    $order = $user->orders()->create($data);
    Mail::send('emails.note', $data, function ($message) use($data) {
        $message->subject('New Order: ' . $data['subject'])
        ->from('myemail@myserver.com')->to($data['email']);
    });
}

我看到你从请求对象中获取了 $data

$data = $request->only('subject', 'email', 'randomid');

但 randomid 是在 created 方法中生成的

    $order = $user->orders()->create([

        'randomid' => rand(100000,999999),
        'subject' => $request->get('subject'),
        'email' => $request->get('email'),
]);

所以请求中没有randomid

我认为你应该像下面这样从 $order 获取 $data:

$data = $order->toArray();

所以你将拥有:

public function store(Request $request)
{
    $order = $user->orders()->create([

            'randomid' => rand(100000,999999),
            'subject' => $request->get('subject'),
            'email' => $request->get('email'),
    ]);

    $data = $order->toArray();

    Mail::send('emails.note',
        $data
        , function($message) use ($data)
        {
            $message->subject('New Order: '.$data['subject'])
                ->from('myemail@myserver.com')
                ->to($data['email']);
        });
}