Sunday, May 5, 2019

Laravel Mail Queue Get Receiver User

Hello,

Recently in one my Laravel project faced an issue where in Mail we have to change content dynamically based on receiver. As we know that when we use Mailable class and mail queue, mail will not sent immediately but it will be processed with Mail Queue. Here we don't have Auth Session or any other information to get receiver user.

To solve this I used following trick.

In mailable class if you check $this variable it will give all such information like this.

from-> => "norply@xyz.com"
address-> : Array[
    0 => Array[
          "address" => "hdave10@gmail.com"
    ]
]

From here you can access email address like this

$emailOfReceiver = $this->to[0]["address"];

And using this you can find user object from Auth\User model or your own model which you used for user information in your laravel project. For my case I was using EmployeeMaster model to get additional information.

Following line I have used in one my Mailable class.

$employee = EmployeeMaster::where("emp_email",$this->to[0]["address"])->first();

Now with this I can write my logic to dynamically change the content of mail.

Hope this helps you.

No comments:

Post a Comment