Laravel 5.8 做个知乎 15 —— 站内信通知
1 创建通知表
php artisan notifications:table
php artisan migrate
2 代码
2.1 \app\Notifications\NewUserFollowNotinfication.php
php artisan make:notification NewUserFollowNotinfication
use Illuminate\Support\Facades\Auth;
public function via($notifiable)
{
// return [\'mail\']; //邮件通知
return [\'database\']; //站内信
}
public function toDatabase($notifiable)
{
return [
\'name\'=> Auth::guard(\'api\')->user()->name,
];
}
2.2 \app\Http\Controllers\Api\FollowersController.php
use App\Notifications\NewUserFollowNotinfication;
public function follow()
{
$userToFollow = $this->user->byId(request(\'user\'));
$followed = Auth::guard(\'api\')->user()->followThisUser($userToFollow->id);
if (count($followed[\'attached\']) > 0 ){
$userToFollow->increment(\'followers_count\');
$userToFollow->notify(new NewUserFollowNotinfication());
return response()->json([\'followed\'=>true]);
}
$userToFollow->decrement(\'followers_count\');
return response()->json([\'followed\'=>false]);
}
notifications表里就会有新增一行
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISM9AnYldnJwAzN9c3PnBnauQ0MlQ0MlcnW3BXbMhXV65UeVRkTzEFRORXQU9EMFRVTxUFVNdXR610MBRVT5FkaNR3ZU1ENVR0T6hTeOdXRq10dJpHT0UERPFzZ61kdjJjYzpkMMRXOykVdNNjW2hXbZVnTtx0dJRUT5N2ViBXO5xkNNh0YwIFSh9CXt92YuM3YltWas5iclN3Ztl2Lc9CX6MHc0RHaiojIsJye.jpg)
3 显示代码
3.1 \app\Http\Controllers\NotificationsController.php
php artisan make:controller NotificationsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class NotificationsController extends Controller
{
//
public function index()
{
$user = Auth::user();
return view(\'notifications.index\',compact(\'user\'));
}
}
3.2 \routes\web.php
Route::get(\'notifications\',\'NotificationsController@index\');
3.3 \resources\views\notifications\index.blade.php
@extends(\'layouts.app\')
@section(\'content\')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">消息通知</div>
<div class="card-body">
@foreach($user->notifications as $notification)
@include(\'notifications.\'.snake_case(class_basename($notification->type)))
@endforeach
</div>
</div>
</div>
</div>
</div>
@endsection
3.4 \resources\views\notifications\new_user_follow_notinfication.blade.php
<li class="notifications">
<a href="{{ $notification->data[\'name\'] }}">
{{ $notification->data[\'name\'] }}
</a> 关注了您哦!
</li>
posted on
2021-07-25 02:16
小白兔晒黑了
阅读(16)
评论(0)
编辑
收藏
举报