一、下载 laravel 5.3
composer create-project laravel/laravel=5.3.* laravel5.3_notifyDatabase
新建数据库 laravel5.3_notifyDatabase
修改 .evn 配置文件
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel5.3_notifyDatabase
DB_USERNAME=laravel5.3_notifyDatabase
DB_PASSWORD=laravel5.3_notifyDatabase
修改中国时区,在 config/app.php 中修改
'timezone' => 'PRC',
二、创建数据
切换目录
cd laravle5.3_notifyDatabase
创建 post model
php artisan make:model Post -m
生成 notifications table
php artisan notifications:table
修改迁移文件:posts_table.php
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->timestamps();
});
}
修改 database/factories/ModelFactory.php
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'title' => $faker->sentence,
'content' => $faker->paragraph,
];
});
执行数据迁移
php artisan migrate
创建用户数据
php artisan tinker
factory('App\User', 5)->create();
创建文章数据
factory('App\Post', 5)->create();
三、notification
创建 PostPublished notification
php artisan make:notification PostPublished
修改 app/Notifications/PostPublished.php
public $post;
public function __construct(\App\Post $post)
{
$this->post = $post;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return $this->post->toArray();
}
注意:这里也可以新增 toDatabase($notifiable) 方法,如果有该方法就会执行该方法,没有的话就执行 toArray($notifiable)
修改 routes/web.php
Auth::loginUsingId(1);
Route::get('/', function () {
$post = \App\Post::find(1);
Auth::user()->notify(new \App\Notifications\PostPublished($post));
});
启动 serve
php artisan serve
访问 http://localhost:8000 进行测试
打开 tinker
php artisan tinker
查看发送的通知
Auth::user()->notifications
可以看到 data 就是刚刚 toArray($notifiable) 返回的数据
四、展示消息
修改 routes/web.php
Auth::loginUsingId(1);
Route::get('/', function () {
return view('welcome');
});
Route::delete('user/notification', function (){
Auth::user()->unreadNotifications->markAsRead();
return redirect()->back();
});
修改视图文件:resources/views/welcome.blade.php
新建视图文件:resources/views/notifications/post_published.blade.php
访问 http://localhost:8000 进行测试
点击标记已读
再次在 tinker 中查看数据
Auth::user()->fresh()->notifications
发现 read_at 字段已记录