尝试使用 laravel 5.4 中的命令发送电子邮件

Trying to send email using command in laravel 5.4

我正在尝试使用 laravel 5.4 中的任务计划程序发送电子邮件,下面是代码

我做了一个邮件控制器

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

# MAiler
use App\Mail\Mailtrap;
use App\Mail\EmailNotification;

class MailController extends Controller
{
    /**
     * Send email
     * @return
     */
    public function index(){
      $user = Auth::user();
      Mail::to($user)->send(new EmailNotification());
    }

}

接下来,我创建了一个命令并在其中使用了控制器

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\MailController;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This will send email';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $mail = new MailController();
        $mail->index();
    }
}

在内核中

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
      'App\Console\Commands\SendNotifications'
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('SendNotifications:notification')
                 ->everyMinute();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

当我尝试使用 web.php 中的路由在控制器中发送电子邮件时,它成功地将电子邮件发送到 mailtrap.io 但是,当我尝试使用此命令在后台发送它时

php artisan SendNotification:notification

我遇到了这个错误

Trying to get property of non-object

我不知道为什么它应该成功,因为它只是调用了控制器中的电子邮件或者我实现了这个错误

你能指导我吗?

因为您在不同的 session 上工作。您可能在浏览器上登录并为此用户创建了 session,但是此 session 在您的命令行中并不相同。

所以你的问题出现在这一行$user = Auth::user();

如果您 dd($user) 在您的控制台命令上,您会注意到 $user 是空的

这就是为什么你得到 try to get 属性 of non object error