Laravel电子邮件,传递变量

时间:2017-08-04 09:30:30

标签: laravel laravel-5 laravel-mail

我正在尝试在Laravel中构建电子邮件,我遇到了这个问题,我想每周一发送电子邮件,因此我想将其作为命令触发并安排它(除非有更好的方法?)这里& #39;是我的电子邮件:

<?php

namespace App\Mail;

use App\Event;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

    class MondayEmails extends Mailable
    {
        use Queueable, SerializesModels;

        /**
         * Create a new message instance.
         *
         * @return void
         */
        public function __construct()
        {
            $events = Event::limit(5)
                ->orderBy('title')
                ->get();
            return $events;
        }

        /**
         * Build the message.
         *
         * @return $this
         */
        public function build()
        {
            return $this->from('support@dev.com')
                        ->view('emails.mondayEmail');
        }
    }

此时$ events确实带回了一个集合。

这是我的邮件视图:

@foreach ($events as $event)
    {{ $event->title }}
@endforeach

和命令:

<?php

namespace App\Console\Commands;

use App\Event;
use App\Mail\MondayEmails;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class MondayEmail extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'email:monday';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Monday Events being send!';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(Request $request)
    {
        Mail::to('dev@gmail.com')->send(new MondayEmails());

    }
}

当我运行它时,我得到:

  

[ErrorException]未定义的变量:events(查看:   C:\ XAMPP \ htdocs中\ liveandnow \资源\视图\电子邮件\ mondayEmail.blade.php)

     

[ErrorException]未定义的变量:events

如何解决这个问题?这是正确的方法吗?或者你会采用不同的方式。

2 个答案:

答案 0 :(得分:1)

构造函数不返回,它允许您设置属性以在类中访问其他函数。如果您在MondayEmails类中尝试以下代码,则可以访问构造函数中返回的电子邮件。

protected $events;
public function __construct()
{
    $this->events = Event::limit(5)
        ->orderBy('title')
        ->get();
}

public function build()
{
    $events = $this->events;
    return $this->from('support@dev.com')
                ->view('emails.mondayEmail', compact('events'));
}

答案 1 :(得分:1)

我想你应该试试这个:

protected $events;
public function __construct()
{
    $this->events = Event::limit(5)
        ->orderBy('title')
        ->get();
}

public function build()
{
    $events = $this->events;
    return $this->from('support@dev.com')
                ->view('emails.mondayEmail')
                ->->with([
                'events' => $events,
              ]);
}

希望这对你有用!!!