Laravel Authentication - Auth::check returns FALSE

此生再无相见时 提交于 2020-06-27 04:06:19

问题


I'm fairly new to Laravel and I'm currently working on a manual authentication for my project.
I have tried Auth::attempt to validate the credentials that have been input, and I have seen that it works since I am being redirected to the page I wanted when it is authenticated.

However, when I try to do Auth::check in the view I have been redirected to, it seems that it returns FALSE and does not read the authenticated user. This makes the certain portion of that view to not be visible. Any insights on this one? Thanks a lot!

Controller

namespace App\Http\Controllers;
use DB;
use Session;
use Illuminate\Http\Request;
use Auth;    
class LoginController extends Controller
{   //    
    public function index()
    {
        return view('view_login');
    }    

    public function verify(Request $request)
    {
        $credentials = $request->only('username', 'password');    
         if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect('dashboard');
        }
        else
        {
            return redirect('/');
        }
    }

View

@if (Auth::check())
     <li><a href="dashboard.html"> Hello {{ Auth::user()->username }}  </a></li>
@endif 

Current Result:

Expected Result:

Update: I've tried to put dd(auth()->user()); after authentication, and I have seen the attributes of the authenticated user. However, after putting this on the Dashboard Controller, it returns NULL. Can someone please help me on this?


回答1:


Check the primary key of your users database. If you set your table's primary key other than id, you need to set it in your User model.

The Laravel Documentation states the following:

Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.

For example, if you have a user_id column set as your primary key in your users database, you need to place the code below in the User model:

protected $primaryKey = 'user_id';




回答2:


Why don't you use Laravel's verification & write your own code in function authenticated instead.

FYI, function attemptLogin need to be call so that user can login.




回答3:


Actually your Authentication works fine, because you can print hello when user authenticated. If you want to prevent access of unauthenticated user you can do this. add this function as the first function of your controller

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

or you can check user in route

Route::get('admin/profile', function () {
    //
})->middleware('auth');

by this ways just authenticated user can see the dashboard page.



来源:https://stackoverflow.com/questions/49891077/laravel-authentication-authcheck-returns-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!