【问题标题】:Laravel - Notifications Controller can't use method user()Laravel - 通知控制器不能使用方法 user()
【发布时间】:2018-09-24 18:58:48
【问题描述】:

我正在尝试将通知系统添加到我的 Laravel 项目中。我看了这个视频来了解系统:https://www.youtube.com/watch?v=iDDUxqpNgSc

通知表、模型和控制器已创建。另外,我用 Vue.JS 和 Pusher 创建了视图。效果很好!

但是,在通知控制器中,当我尝试使用 Auth::user() 方法时,它返回 null。我在某处读到这是因为在控制器加载时中间件“auth”尚未加载。

这是我的 NotificationsController 文件:

    <?php

namespace App\Http\Controllers;

use App\Notification;
use Illuminate\Http\Request;
use App\Idea;
use App\User;
use Illuminate\Support\Facades\Auth;

class NotificationsController extends Controller
{
    public function __construct()
    {
    }

    function get(){
        $notification = Auth::user()->unreadNotifications()->get();
        return $notification;
    }
    function read(Request $request){
        Auth::user()->unreadNotifications()->find($request->id)->markAsRead();
    }
}

你知道如何解决这个问题吗? 感谢您的宝贵时间!

【问题讨论】:

  • Auth 方法在构造函数中不可用(因为会话中间件尚未运行),但在其他方法中可用。所以在你的情况下,你只是没有登录。
  • 可以确定,我登录了(我在右上角看到用户名)但是什么也没有,auth return null
  • 如何设置路线?
  • 这是该控制器的路由://Route for notif Route::post('/notification/get','NotificationsController@get')-&gt;middleware('auth'); Route::post('/notification/read','NotificationsController@read')-&gt;middleware('auth');

标签: laravel authentication controller notifications


【解决方案1】:

答案与 Auth::user 无关(它是可访问的)。我刚刚在我的模型中定义了 notifiable_type。是 App\Idea,应该是 App\User

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多