laravel 5.4 auth facade不起作用

时间:2017-07-28 02:31:15

标签: php laravel authentication

Laravel 5.4 Auth外观不起作用。 auth中间件正常运行。正如预期的那样,对受保护路由的调用会生成登录页面。格式错误的凭据会产生预期的错误。正确的凭据会按预期生成正确的页面。评论出“使用Illuminate \ Support \ Facades \ Auth;”这一行产生错误“类'App \ Http \ Controllers \ Admin \ Auth'未找到”,如预期的那样。

具体来说,Auth :: check()产生false,尽管登录成功,Auth :: user()也不返回任何内容。调用Auth外观的这些实现之一不会产生错误。

此代码在Laravel 5.2中运行良好。我所知道的唯一偏离程序是在迁移到Laravel 5.4期间,我没有在新的Laravel实现中运行命令“php artisan make:auth”。

搜索“laravel 5.4 auth facade不起作用”不会在Bing或stackoverflow内部搜索引擎中产生相关结果。

显示相关代码,如下所示:

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use App\Models\Admin;
use App\Models\Role;
use App\Models\Role_user;
use App\Models\Client;
use App\Models\Contact;
use App\Models\PublicPages;
use App\Models\Survey_question;
use App\Models\Survey_item;
use App\Models\Survey_project;
use App\Models\State;
use App\Models\Test_post;
use App\Models\Registration;
use Hash;
use Redirect;
use DB;
use Illuminate\Support\Facades\Auth;
use App\Classes\RoleHelper;
use App\Classes\CommonCode;

class AdminController extends Controller
{
var $obj_logged_in_user;
var $arr_logged_in_user;
var $bool_has_role;
var $roleHelper;
//organization of function
// 1. __construct
// 2. index
// get, alphabetically
// post, alphabetically

public function __construct(
        Role_user $role_user, RoleHelper $roleHelper, Request 
$request)
{   

    $this->middleware('auth');
    echo "<pre>";
    echo "admin controller, line 50<br>";
    print_r($request->user);
    echo "</pre>";
    // line 49 (request->user) produces nothing

    if (Auth::check())
    {

        $this->middleware('role:admin');
        $this->obj_logged_in_user = Auth::user();
print_r($this->obj_logged_in_user);
// line 58 (print_r) produces nothing
        $this->arr_logged_in_user = $roleHelper->prepare_logged_in_user_info($this->obj_logged_in_user);

    }  // end if Auth::check()

} // end __construct function

总之,我希望Auth :: check()返回准确的结果,并让Auth :: user()返回登录的用户对象。先感谢您。

1 个答案:

答案 0 :(得分:0)

如果您想在Auth方法中使用__construct()函数,则需要将其传递给闭包内的$this->middleware()

public function __construct(Role_user $role_user, RoleHelper $roleHelper)
{
    $this->middleware('auth');
    $this->middleware('role:admin');
    $this->middleware(function ($request, $next) use ($role_user, $roleHelper) {

        if (Auth::check()) {

            $this->obj_logged_in_user = Auth::user();
            $this->arr_logged_in_user = $roleHelper->prepare_logged_in_user_info($this->obj_logged_in_user);

        }  

        return $next($request);
    });
}

另外,仅仅是一个FYI,您可能会发现使用Laravel附带的dump()dd()函数更容易。而不是写:

echo "<pre>";
echo "admin controller, line 50<br>";
print_r($request->user);
echo "</pre>";
你可以写一下:

dump('admin controller, line 50', $request->user);

https://laravel.com/docs/5.4/helpers#method-dd

希望这有帮助!