首页 > 解决方案 > laravel 5.6未定义变量:尝试发送电子邮件时的用户

问题描述

我正在尝试使用我不熟悉的 laravel 5.6 中的 Notification 类发送电子邮件。

我正在尝试传递用户和书籍信息,但每次我得到以下信息:

未定义变量:用户

这是我的successEmail.php:

  <?php

namespace BOOK_DONATION\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class successEmail extends Notification
{
    use Queueable;
    public $user;
    public $book;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($user,$book)
    {
        //
        $this->user=$user;
        $this->book=$book;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
        ->greeting('Dear'.$user->name.'thak you for creating donation for '.$book->name);    
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

这是调用类successEmail的函数:

 public function doBook(Request $request){
            $validatedData = $request->validate([
                'title' => 'string|required|max:255',
                'Author'=> 'string|required|max:255',
                'Cover_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                'Book_description'=>'string|required|max:255',

            ]);
        $path= $request->Cover_image->store('images');
        $uid=Auth::user()->id;
        $country=Auth::user()->country;
        $city=Auth::user()->city;
        $book=Book::create(['title'=>$request->input('title'),
                       'Author'=>$request->input('Author'),
                       'user_id'=>$uid,
                       'country'=>$country,
                        'city' =>$city,
                        'Book_description'=>$request->input('Book_description'),
                        'path'=>$path,
                        ]);
         $user = Auth::user();

         $user->notify(new successEmail($user,$book));

        return redirect('/donation/create')->with('status', 'Thank you for your donation');
    }

如您所见,我将 user 和 book 变量传递给构造函数并将它们声明为 public 那么我缺少什么?

标签: phplaravellaravel-5.2

解决方案


这些变量不存在于函数作用域中,但它们确实作为类属性存在,因此应该这样对待它们。

return (new MailMessage)
    ->greeting('Dear '.$this->user->name.' thank you for creating donation for '.$this->book->name);

推荐阅读