Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rushand's avatar

Load Custom Data Tables on Session

{{Auth::user()->name }}

Returns the details of current authenticated user, likewise is it possible to retrive data other tables which has a foreign key from users table.

ex: If a Student logged in I need to display logged Students Name, Or a Teacher logged in I need to display logged teachers name,

These names should be shown in a admin layout which included in every view throughout the application Both teacher and student tables has foreign key user_id which refers user table

How to do this?

0 likes
1 reply
MichalOravec's avatar

If you have set your relationship you can get it like

{{ Auth::user()->student->name }}

But for to show online users you can use this middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class LogLastUserActivity
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            Cache::put("user-{$request->user()->id}-is-online", true, now()->addMinutes(5));
        }

        return $next($request);
    }
}

And add it to middlewareGroups under web key in app/Http/Kernel.php

In EventServiceProvider

Logout::class => [
    ForgetLastUserActivity::class,
],
<?php

namespace App\Listeners\Auth;

use Illuminate\Auth\Events\Logout;
use Illuminate\Support\Facades\Cache;

class ForgetLastUserActivity
{
    /**
     * Handle the event.
     *
     * @param  Logout  $event
     * @return void
     */
    public function handle(Logout $event)
    {
        if ($event->user && Cache::has($key = "user-{$event->user->id}-is-online")) {
            Cache::forget($key);
        }
    }
}

In User model

public function isOnline()
{
    return Cache::has("user-{$this->id}-is-online");
}

Or instead of cache use another table where you will store logged in users. And in the administration you show users from that table. Of course you can save there type for Student or Teacher.

Please or to participate in this conversation.