创建通知:php artisan make:notification InvoicePaid
这条命令会在 app/Notifications
目录下生成一个新的通知类。
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class InviocePaid extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels. 设置通知频道
*
* @param mixed $notifiable
via方法接收一个 $notifiable 实例。这个实例将是通知实际发送到的类的实例。你可以用 $notifiable 来决定通知用哪些频道 来发送:
* @return array
*/
public function via($notifiable)
{
//database测试数据库频道,mail是测试邮箱频道
return ['mail','database'];
}
/**
* Get the mail representation of the notification.发送邮箱内容
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
//插入数据库内容
public function toDatabase()
{
return ['name'=>'xx'];
}
}
具体看注释。
为了测试数据库频道,数据表新建通知表,存储所有的通知消息;由于创建用户user包含mail属性,邮箱频道无需操作。
# 创建表 php artisan notifications:table # 数据库迁移 php artisan migrate
这里就用系统默认的 App\User
模型使用这个 trait,它包含着一个可以用来发送通知的方法: notify
。 notify
方法需要一个通知实例做参数,于是就在注册控制器的新建用户方法中调用:
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use App\Notifications\InvoicePaid;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->notify(new InvoicePaid());//在这里调用
return $user;
}
}
以上即可,至于队列调用,再说。