mysqllaraveleloquentmailtrap

Sending Email to Users with Different Roles in Laravel 7 using Mailtrap


I am making an e-commerce website in which I want to send emails to users with different roles once order was completed. I was able to do this for a specific role only but how do I do this for different roles? Since normal users can be sellers and sellers can also order products from other sellers. So far these are the steps I've tried:

OrderController.php

$users = User::whereHas('role', function ($q) {
        $q->where('name', 'user', 'seller');
    })->get();

    Mail::to($users)->send(new OrderCompleted($suborder));

However, this only works and sends email to the user roles and not the seller roles.

This is my mail model:

OrderCompleted.php

public $suborder;

public function __construct(SubOrder $suborder)
{
    $this->suborder = $suborder;
}

I have also tried Mail::to($suborder->user->email)->send(new OrderCompleted($suborder)); wherein my SubOrder.php model are as follows:

 public function user()
{
    return $this->belongsTo(User::class);
}

But when I try to use this second query, I get an error Trying to get property 'email' of non-object

How do I make this happen? Any advice would be much appreciated. Thank you!


Solution

  • I was able to send emails to target user emails regarless of their roles using

    Mail::to($suborder->order->user->email)->send(new OrderCompleted($suborder));
    

    Thank you so much!