使用Notification实现点赞、收藏功能

来源:互联网 发布:fastcopy 网络拷贝 编辑:程序博客网 时间:2024/06/16 19:57

1 创建notification

php artisan make:notification PostPublished

此时app\Notifications目录中有PostPublished.php文件,打开该文件。可以看到下面的方法内容。

public function via($notifiable){    //这里可以有多种配置,可以时mail,也可以是datebase——站内信通知    return ['mail'];    //站内信    //return ['database'];}public function toMail($notifiable){    return (new MailMessage)                //也可以通过subject方法直接定义邮件主题                ->subject('A Post published'.$this->post->title)                //如果想改变中间蓝色框,可以增加success设置。                ->success()                //对原代码进行修改                //->line('The introduction to the notification.')                ->line('new post on laracist:'.$this->post->title)                //Natification Action的链接即是https://laravel.com                //->action('Natification Action', 'https://laravel.com')                ->action('Read It Now',url('/post/'.$this->post->id))                ->line('Thank you for using our application!');}

这里写图片描述

关于图片中的最上/下一行My Application文字可以通过config\app.php修改。

//原代码文字//'name'=>'My Application',//修改为'name'=>'欢迎您!',

2 打开web.php路由

Route::get('/',function(){    //查找Id为2的用户,查考post为4的数据    $user=\App\User::find(2);    $post=\App\Post::find(4);    //实例化1中创建的PsrtPblished.php类,同时将参数$post传入    $user->notify(new \App\Notification\PostPublished($post));});

3 PostPublished.php文件中接受路由中传来的参数

class PostPublished extends Notification{    use Queueable    //定义一个$post属性    public $post;    //构造函数中自动加载传参,post参数依赖注入    public fucntion __construct(Post $post)    {        $this->post=$post;    }    //其他地方不作变动}

4 mail.php配置

config\mail.php文件配置

'from'=>[    'address'=>'fa_song_zhe@126.com',    'name'=>'fa_song_zhe',

5 .env文件

邮件配置

MAIL_HOST=mailtrap.io //追踪邮件的发送

打开mailtrap.io网站进行注册。将SMTP Setting下的SMTP中的Username和Password的值拷贝到.env文件中
这里写图片描述
将其中的username和password两项内容

Username:   98e5a5ee33a592Password:   743c72d10a8i47

填到.env文件中(约在第26~30行)

MAIL_DRIVER=smtpMAIL_HOST=smtp.mailtrap.ioMAIL_PORT=2525MAIL_USERNAME=98e5a5ee33a592MAIL_PASSWORD=743c72d10a8i47MAIL_ENCRYPTION=null

配置完成,这时触发路由文件则会向smtp.mailtrap.io邮件中发送邮件。

6 执行vendor:publish

php artisan vendor:publish//此时会显示Copied Directory [/vendor/laracel/framework/src/Illuminate/Notifications/resources/views] to [/resources/views/vendor/notifications]Copied Directory [/vendor/laracel/framework/src/Illuminate/Pagination/resources/views] to [/resources/views/vendor/pagination]

此时文件目录
resources\vews\vendor\notifications\email.blade.php
之后再修改邮件内容是只需修改email.blade.php文件内容即可。

原创粉丝点击