public function via($notifiable) { return ['mail']; }
1.新建notification類php
php artisan make:notification PostNotification
2.設置路由web
//notification 注意默認發送到user模型中的email郵箱帳號 因此要確認user郵箱可用 Route::get('/notification',function(){ $user = \App\User::find(1); $post = \App\Post::find(2); $user->notify(new \App\Notifications\PostNotification($post)); });
3.訪問/notification 收到郵件數據庫
4.經常使用設置方法 PostNotification.phpapp
public function toMail($notifiable) { return (new MailMessage) ->subject('A post published'.$this->post->title) //自定義主體 ->success() //定義按鈕顏色 ->line('The introduction to the notification.') ->action('Notification Action', url('/')) ->line('Thank you for using our application!'); }
1.修改PostNotification.phppost
public function via($notifiable) { //return ['mail']; return ['database']; }
2.建立notification遷移文件this
php artisan notifications:table php artisan migrate
3.PostNotification.php 中可添加 toDatabase方法 若是沒寫的話默認用的是toArray方法
url
4.修改web.php
code
5.查看當前用戶下的notifications
orm
6.新建一個notificationcsrf
php artisan make:notification UserSubscribe
7.UserSubscribe.php 修改以下
public function via($notifiable) { return ['database']; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ 'subscribed_at' => Carbon::now() ]; }
8.修改web.php
//notification Route::get('/notification', function () { $user = \App\User::find(1); $post = \App\Post::find(2); //$user->notify(new \App\Notifications\PostNotification($post)); $user->notify(new \App\Notifications\UserSubscribe()); });
9.再次查看當前用戶的notifications
10.列出未讀notifications並標識爲已讀
web.php
//notification Route::get('/show-notification', function () { return view('notifications.index'); }); //標識未讀 Route::delete('user/notification',function (){ Auth::user()->unreadNotifications->markAsRead(); return redirect()->back(); });
notifications.index.blade
@extends('app') @section('content') <h1>個人通知:</h1> <ul> @foreach(Auth::user()->unreadNotifications as $notification) @include('notifications/'.snake_case( class_basename($notification->type) )) @endforeach </ul> <form action="/user/notification" method="POST"> {{csrf_field()}} {{method_field('DELETE')}} <input type="submit" value="標識已讀"> </form> @stop
user_subscribe.blade.php
<h2>user</h2> {{$notification->data['subscribed_at']['date']}}
post_notification.blade.php
<h2>post</h2> <li>{{$notification->data['title']}}</li>
標識某條已讀
$user->refresh()->unreadNotifications->where('id','57bb0e0e-8d35-4da8-850b-121a5317c9b9')->first()->markAsRead();
database