Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

laravel - Pass model to mail view

I have several methods that require email submissions. An example is, after making a purchase.

My class Mailable

<?php

namespace AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
use AppModelsOrder;

class AfterOrder extends Mailable
{
    use Queueable, SerializesModels;

    
    public $order;

    public function __construct(Order $order)
    {
        $this->Order = $order;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {

        
        return $this->subject('Thanks for your purchase')->view('mail.after-order');
    }
}

My mail view

<div class="container">
    <h1>Nombre: {{Auth::user()->email}}</h1>
    <h1>Order: {{$order->reference}}</h1> 
</div>

My Controller

public function sendMail(Order $order) {
        $order = $order->newQuery();
        
        $order->whereHas('user', function($query){
                $query->where('email', '=', Auth::user()->email);
            });
            
       $order = $order->orderBy('id', 'desc')->first();    

        $user = User::where('email', '=', Auth::user()->email)->first();
        Mail::to($user->email)->send(new AfterOrder($order));


        //return redirect()->route('home')->with(['message' => 'Thank you for shopping at Sneakers!']);
    }

What am I doing wrong? If I, for example, in my controller make a $ order-> reference I get the order reference but when passing the variable to the view it treats me as null or empty

question from:https://stackoverflow.com/questions/65872766/pass-model-to-mail-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use the with method

public function build()
{
    return $this->view('mail.after-order')
                ->with([
                   'orderName' => $this->order->name,
                   'orderPrice' => $this->order->price,
    ]);
}

in your mailable class AfterOrder. With that you have access to the name and the price of the order in your mail view.

You can then access these with {{ $orderPrice }} and {{ $orderName }} in your view.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...