ekpono's avatar
Level 12

I want to get last logged in date from my user. The database isn't updating

Here is my table Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->datetime('last_login')->nullable(); $table->rememberToken(); $table->timestamps(); });

AuthenticatesController public function authenticated(Request $request, $user) { $user = auth()->user(); $user->last_login = date('Y-m-d H:i:s'); $user->save(); } The table is still empty when i login My user model has included last_login in fillable

0 likes
16 replies
ekpono's avatar
Level 12
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->datetime('last_login')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
ekpono's avatar
Level 12
        $user = auth()->user();
        $user->last_login = Carbon::now();
        $user->save();
    }
Snapey's avatar

please format your code correctly

            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->datetime('last_login')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
public function authenticated(Request $request, $user)
{
    $user = auth()->user();
    $user->last_login = Carbon::now();
    $user->save();
}

what is AuthenticatesController ?

You see in your authenticated function, the second property is the user. You dont need to load it again.

Snapey's avatar

does your authenticated function even get called?

ekpono's avatar
Level 12

Yes. am using default laravel auth command

Snapey's avatar

So? there is no AuthenticatesController?

ekpono's avatar
Level 12

yes.. i meant to say AuthenticatesUsers trait

ekpono's avatar
Level 12

I want to get last logged in user time.

jaythanki's avatar

@ekpono can do

public function authenticated(Request $request, $user) 
{ 
$user = Auth::User();
 if ($user != null && $user != "")
 {
  $loginedIn = User::where('id', Auth::id())->update(['last_login' =>Carbon::now()]);
 }
}
jaythanki's avatar

@ekpono can you share your controller code and database screenshot if u dnt mind

ekpono's avatar
Level 12

Users Table

        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->datetime('last_login_at')->nullable();
            $table->string('last_login_ip')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

AuthenticatesUser traits
public function authenticated(Request $request, $user) 
    { 
        $user = Auth::User();
        if ($user != null && $user != "")
            {
                $loginedIn = User::where('id', Auth::id())->update(['last_login_at' => Carbon::now()]);
            }
    }
tqt_andrew's avatar

~~Have you added last_login_at to the fillable array on the User model given that it's a custom field?~~

// I should have read your initial post better the first time.

Upon a good read through, your code snippets seem to alternate between last_login_at and last_login are you sure that they are in sync on both your model and controller method? Also, if you've updated them it brings us back to my first response, did you update the fillable array when you made this change?

You should be able to shorten your method too considering that logic prior to this method has ensured that there is a user:

public function authenticated(Request $request, $user) 
{
    $user->last_login_at = Carbon::now();
    $user->save();

    return redirect()->intended($this->redirectPath())
}
ekpono's avatar
Level 12
        'name', 'email', 'password','gender','last_login_at', 'last_login_ip',
    ];

yes.

last_login_at is used consistently.

ekpono's avatar
ekpono
OP
Best Answer
Level 12

Finally used event listener

App\Listener\UpdateLastLoginAt

<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Carbon\Carbon;
class UpdateLastLoginAt
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Login  $event
     * @return void
     */
    public function handle(Login $event)
    {
        $event->user->last_login_at = Carbon::now();
        $event->user->save();
    }

App\Providers\UpdateLastLoginAt

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\Event' => [
            'App\Listeners\EventListener',
        ],
        'Illuminate\Auth\Events\Login' => [
            'App\Listeners\UpdateLastLoginAt',
    ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        //
    }
}

That worked for me

Please or to participate in this conversation.