Renzeee
Renzeee

Reputation: 655

Laravel's Auth::attempt() returns true but Auth::check() returns false

As the title says, Laravel's function Auth::attempt() returns true in the following code section (with unimportant parts deleted):

public function doLogin()
{
    $validator = [..]

    if ($validator->fails()) {
        [..]
    } else {
        $userdata = array(
            'username'  => Input::get('username'),
            'password'  => Input::get('password')
        );

        if (Auth::attempt($userdata, true)) {
            return Redirect::to('/');
        } else {        
            return Redirect::to('login');
        }
    }
}

But when we are redirected, we try to check if an user is really logged in with Auth::check(), and it returns false somehow.

We have tried every possible solution on Google and did not succeed with any of it. For example we added a remember_token but it did not change anything, though it proved us that the Auth::attempt() does something because the remember_token is set in the database.

As a last resort, we even tried to print something in the Auth::attempt() method of Laravel in ./vendor/laravel/framework/src/Illuminate/Auth/Guard.php but we did not see anything of that, not even with print_r. We tried to find other attempt-functions in the complete codebase but none is found.

It could be that something about changing User to an translated form of it makes it broken, but then the function Auth::attempt() should also be broken, probably.

It seems that something really magical happens but we have no idea what or how. Does anybody else have an idea?

Upvotes: 5

Views: 5525

Answers (3)

linh dinhvan
linh dinhvan

Reputation: 61

I encountered a similar error, at login then redirest, Auth::user() returned null.

I discovered the culprit is the data type of created_at, updated_at which is string. The solution is to convert the string data type to mongoDB date

In other cases I suggest checking your user table, there may be a mistake somewhere

Upvotes: 1

Hossein Karami
Hossein Karami

Reputation: 806

for those who still have this problem, if your primary key doesnt follow autoIncrement, you should add this following code to your User model:

public $incrementing=false;

and if you have changed your primary column name, add this:

protected $primaryKey = 'vid'; //changed to vid

Upvotes: 1

abdawoud
abdawoud

Reputation: 219

By default, Laravel assumes that each table has a primary key called id.

Possible solution is to do this in your model:

protected $primaryKey = 'id'; //Or what ever id name do you have.

This error may occur if you are trying to use laravel-mongodb with custom increment and unique generated id rather than the default _id from MongoDB. The solution in this case is not to name your custom id like this 'id' because it will make Laravel confused. However, name it anything else.

Upvotes: 7

Related Questions