laravel5.3-第9章-notifyDatabase laravel5.3-第9章-notifyDatabase

2023-06-30

一、下载 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

https://file.lulublog.cn/images/3/2023/06/kmmCgNV88M7k0Z0R7Wm5QK4mMMzRvm.jpg

可以看到 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

https://file.lulublog.cn/images/3/2023/06/BG7975fIWu3q77FoOK5NZd1Z05Q7Gz.jpg

新建视图文件:resources/views/notifications/post_published.blade.php

https://file.lulublog.cn/images/3/2023/06/rSsQN2kFcvNl7sKSs88Q29QY7qKdqY.jpg

访问 http://localhost:8000 进行测试

https://file.lulublog.cn/images/3/2023/06/ySv8z7tCwUYRFtzcSldy7cU8bJffRu.jpg

点击标记已读

https://file.lulublog.cn/images/3/2023/06/fPl9p4X9BL4pXYmBl4po9B29No4PbB.jpg

再次在 tinker 中查看数据

Auth::user()->fresh()->notifications

https://file.lulublog.cn/images/3/2023/06/mMKwSEv3Q33a3MHWxyKQeeKeQm46y3.jpg

发现 read_at 字段已记录

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开微信扫一扫,即可进行扫码打赏哦

阅读 250