1 创建通知表
php artisan notifications:table
php artisan migrate
2 代码
2.1 appNotificationsNewUserFollowNotinfication.php
php artisan make:notification NewUserFollowNotinfication
use IlluminateSupportFacadesAuth;
public function via($notifiable) { // return ['mail']; //邮件通知 return ['database']; //站内信 } public function toDatabase($notifiable) { return [ 'name'=> Auth::guard('api')->user()->name, ]; }
2.2 appHttpControllersApiFollowersController.php
use AppNotificationsNewUserFollowNotinfication;
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表里就会有新增一行
3 显示代码
3.1 appHttpControllersNotificationsController.php
php artisan make:controller NotificationsController
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use IlluminateSupportFacadesAuth; class NotificationsController extends Controller { // public function index() { $user = Auth::user(); return view('notifications.index',compact('user')); } }
3.2 outesweb.php
Route::get('notifications','NotificationsController@index');
3.3 esourcesviews otificationsindex.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 esourcesviews otifications ew_user_follow_notinfication.blade.php
<li class="notifications"> <a href="{{ $notification->data['name'] }}"> {{ $notification->data['name'] }} </a> 关注了您哦! </li>