2017-09-05 130 views
0

我想在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

我不知道爲什麼它被認爲是成功的,因爲它只是叫控制器中的電子郵件或我實現了這個錯誤

你能指導我嗎?

回答

1

因爲你在不同的會議上工作。您可能已登錄瀏覽器併爲此用戶創建了會話,但此會話在您的命令行中不相同。

所以在這行中出現的問題$user = Auth::user();

如果dd($user)在控制檯的命令,你會發現$用戶是空

而這就是爲什麼你得到試圖獲得非對象的屬性錯誤

相關問題