8

I am new to laravel and I am working with a functionality where we insert data in user table with

DB::insert();

After that i get last id with

$user_id = DB::getPdo()->lastInsertId();

Now I want user to login after register and I am trying to

Auth::loginUsingId($user_id);

But its returning me false. I also tried

$user = User::find($user_id);
Auth::login($user);

Its also return null $user.

Please help...

Saromase
  • 467
  • 5
  • 10
Anuj kumar
  • 81
  • 1
  • 1
  • 4
  • Is the table you store your user in called `users` ? in which tables are you doing `DB::insert()` and `$user_id = DB::getPdo()->lastInsertId()` ? – Mike Jan 29 '19 at 10:30
  • @Mike yes its name is users. – Anuj kumar Jan 29 '19 at 10:32
  • What is the contents of `$user_id` ? and is the user saved in the table with that same id ? – Mike Jan 29 '19 at 10:33
  • $user_id is the id the last insert id in users table while inserting record , its returning me id, but the issue in login when i passing this id its returning false – Anuj kumar Jan 29 '19 at 10:36
  • The [`login`] ( https://laravel.com/api/5.7/Illuminate/Contracts/Auth/StatefulGuard.html#method_login ) method has no return value. what happens if you dump `auth()->user()` after you performed a login – Mike Jan 29 '19 at 10:40
  • its returning null. For yor info I also tried with old users id manually like Auth::loginUsingId(10) then its logging in. May be the issue of fields – Anuj kumar Jan 29 '19 at 10:44

4 Answers4

9

This worked for me

Auth::loginUsingId(1);

Godstime John
  • 253
  • 3
  • 8
5

Login User:

Auth::login($user);

check current user is login or not:

Auth::check();
atf.sgf
  • 458
  • 2
  • 4
  • 16
2

Auth:login returns void so you can try something like this to check if user is logged in or not:

Auth::login($user);
return [
    'status' => Auth:check()
];

check() determine if the current user is authenticated or not.

Iftikhar uddin
  • 3,117
  • 3
  • 29
  • 48
0

So, can you show your user Model?

In the Laravel Docs (https://laravel.com/docs/5.7/authentication) you can see, that your model must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract.

The basic User model looks like:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

and thats working lice expected.

Matz
  • 1,006
  • 10
  • 27