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

460 views Asked by At

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!

2

There are 2 answers

0
Jemy On BEST ANSWER

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!

8
bhucho On

By your this line, "sends email to the user roles and not the seller roles.". I believe that you want to check name for both 'user' & 'seller'. So change your query,

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

Your $q->where is only chacking for second argument i.e user in the case.

And for your second question I believe @sta is correct.