1

I want to send the data of the last order just made by the user

I already have my .env configured

AfterOrder Class: (Class type mail)

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use App\Models\Order;

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->view('mail.after-order');
    }
}

View:

<div class="container">
    <h1>Name: {{$order->user->name}}</h1>
</div>

the user table is a belongsto of orders

Controller:

public function sendMail(Order $order) {
        $order = $order->newQuery();
        
        $order->whereHas('user', function($query){
                $query->where('email', '=', \Auth::user()->email);
            });
            
        $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!']);
    }

Whats wrong? i got this error

enter image description here

1
  • did you mean to capitalize $this->Order in the AfterOrder constructor? Commented Jan 24, 2021 at 3:35

1 Answer 1

2

$order is still a Builder object when you do this.

$order->orderBy('id', 'desc')->first();

To get the actual Model, you need to do the following:

$order = $order->orderBy('id', 'desc')->first();
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. That was the solution. One more question, excuse me, why is the view's $order->user->name returning me null?
I'm not sure. Maybe its value is null or empty in the database. Have you tried eager-loading it by either calling ->with('user') before first() or $order->load('user') in your mail constructor?
Sorry, it was my mistake. The value that gives me null is the reference column of the Order table. In user it does not give me null because I get it directly from \Auth::user That is my code what return null <h1>Order Reference: {{$order->reference}}</h1>
I'm not sure if you still have that typo in your code but in your constructor it should be $this->order and not $this->Order. Also, have you checked if the reference is null in the database?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.