Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 控制器中的Laravel,Auth::user()_Php_Laravel - Fatal编程技术网

Php 控制器中的Laravel,Auth::user()

Php 控制器中的Laravel,Auth::user(),php,laravel,Php,Laravel,Laravel框架-为什么我不能在Laravel项目的控制器中使用Auth::user(),(查看用户是否已登录)。会话是否未连接到控制器 HomeController.php public function isauthorized(){ if (Auth::user()){ return View::make('home.basic') ->with('basic1', 'Authorized'); }else{

Laravel框架-为什么我不能在Laravel项目的控制器中使用Auth::user(),(查看用户是否已登录)。会话是否未连接到控制器

HomeController.php

 public function isauthorized(){
    if (Auth::user()){
        return View::make('home.basic')
            ->with('basic1', 'Authorized');
    }else{
        return View::make('home.basic')
            ->with('basic1', 'Not Authorized');
    }
}

我的登录系统正在工作,并且在登录时始终设置会话。当我在View或routes.php中调用函数Auth::user()时,它成功了。但是当我调用控制器中的函数时,它是错误的。请提供帮助。

若要查看用户是否已登录,请不要使用
Auth::user()
。改用
Auth::check()

if (Auth::check()){
    return View::make('home.basic')->with('user', Auth::user());
}

问题是您没有包括Auth facade

在HomeController.php中,请执行以下操作:

use Illuminate\Support\Facades\Auth;

使用
Auth::check()
函数检查用户是否已登录

如果您使用的是Laravel 5.x,则可能会有Auth中间件组件。这可能是缺失的环节

我经常在控制器中使用这样的模式:

public function __construct()
    {
        $this->middleware('auth');
        $this->user =  \Auth::user();
    }
那你可以

if($this->user..)


如果($this->user->can('something'))
只需在控制器库中添加以下内容

use Illuminate\Support\Facades\Auth;

您需要在控制器中使用Auth facade

在类定义之前添加此行

use Auth;
使用Auth 我也有同样的问题。我找到的解决方案是不使用\Auth::user()(它返回null)。相反,要像这样检查保护:
\Auth::guard('mrm')->User()
。显然,将“mrm”替换为您正在使用的任何auth guard

这样做可以正确地返回当前用户,即使Auth::user返回null,您也可以对其使用其他方法,例如
\Auth::guard('mrm')->check()
,而不是
\Auth::check()
(始终返回false)


不知道为什么Auth facade不起作用,但至少有一种替代方法可以起作用。

在控制器构造函数中:

public function __construct(){
    $this->middleware('auth');
}

此外,您还可以使用
auth()
帮助程序,而无需在控制器中添加外观。(即
auth()->user()

简单调试。使用
dd(auth::user());
在您的
if
之前。确保应用程序/存储目录可由Web服务器写入这与今年早些时候提供的解决方案相同。当您回答问题时,确保在现有答案的基础上添加值。谢谢!为什么
Auth::check()
会更好?我引用:换句话说,Auth::check()调用Auth::user(),从中获取结果,然后检查该用户是否存在。主要区别在于,它会为您检查该用户是否为null,以便获得布尔值。stackoverflow.com/a/33483798/460885