Home > Net >  Laravel : send email to other_emails
Laravel : send email to other_emails

Time:11-15

I'm trying to send an email to other_emails, so that when the user 1 already book for his friends, the user 1 got email and his friends also got an email, i tried to use foreach for sending the email the other_emails but i got this error message Undefined variable: isi_email1

How can i fix it?

The Controller :

$isi_email1 = [
            'title'=>'Thank you for your purchase',
            'body'=>'Please give us your review about your experience using Pintunuswantara Travel. Link : https://pintunuswantara.com/review' 
        ];
        
        $subject = [$booking->email];
        Mail::to($subject)->send(new OthersEmail($isi_email1));
        
        $others = Booking::select('other_emails');
        foreach($others as $other){
            Mail::to($other)->send(new OthersEmail($isi_email1));
        }

The OthersEmail :

 public $isi_email1;
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
        $this->isi_email1 = $isi_email1;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        
        return $this->from('[email protected]')
                    ->subject('Thank you')
                    ->view('other_email');
    }

CodePudding user response:

The problem seems to be the variable scope/context. In order for you to access a variable in a function within a class, you must pass it in as a parameter; it doesn't inherit the context of where its called.

IE: in this example, your OthersEmail::construct function must accept the $isi_email1 parameter in order to then assign it to its property.

Change the constructor function to look like this in order to then assign and be able to pass through the variable:

public function __construct(array $isi_email1) {
    $this->isi_email1 = $isi_email1;
}

If you don't intend on using typed parameters, you can remove the array from the parameter definition.

public function __construct($isi_email1) {
    // etc.
}

Your controller class is already trying to pass the variable in, so there shouldn't have to be any changes there in order for this to work.

  • Related