【发布时间】:2019-12-05 21:55:10
【问题描述】:
我如何创建一个工匠命令来向系统中的所有用户发送数据库通知,其中包含他们在系统中停留了多长时间的信息?
我的 SendEmails 命令如下所示:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\User;
use Illuminate\Support\Facades\Mail;
use App\Mail\UserEmails;
use Illuminate\Support\Facades\Notification;
class SendEmails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'send:emails';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send Email to allusers';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$users = User::all();
foreach($users as $user){
$created_at = $user->created_at;
Notification::send($user, new SendEmailsNotification($created_at));
}
}
}
然后我创建了通知表,进行了迁移,代码如下:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class SendEmailsNotification extends Notification
{
use Queueable;
public $created_at;
public function __construct($created_at)
{
$this->created_at = $created_at;
}
public function via($notifiable)
{
return ['database'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
public function toArray($notifiable)
{
return [
];
}
}
用户.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
//use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'address', 'image'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
//'email_verified_at' => 'datetime',
'address' => 'array'
];
protected $uploads = '/images/';
public function getImageAttribute($image){
return $this->uploads . $image;
}
public function contacts(){
return $this->hasMany('App\Contact');
}
}
当我运行 artisan 命令“php artisan send:emails”时,我在控制台中看到以下错误:
BadMethodCallException : 调用未定义的方法 App\User::routeNotificationFor()
如何将通知发送给所有用户?
【问题讨论】:
-
@Rwd 我刚刚编辑了我的问题
-
抱歉,您能否展示整个类,即正在导入哪些类以及它使用的特征。
-
@Rwd 我刚刚编辑了我的问题
-
您是否有理由将
created_at传递给每个通知? -
是的@Rwd。因为通知的内容需要在人类可读的时间内指定用户成为会员的方式
标签: php laravel laravel-artisan