Randeep Singh Randeep Singh - 6 months ago 9
PHP Question

How to get userId from database without Auth::()?

I want to get current userId from database without Auth::() and I don't want to get it from route like

'/xxx/{id}'


Is there any other way to get the userId without Auth::()?

eg.
$userId = User::where('id', $id)->pluck('id');


Here is my auth::controller declaration :

public function getLogout(Request $request)
{

$redis = \Redis::connection();
$user = $request->user();

if ($user) {
$userID = $user->id;
}
// $userId = User::where('id', $id)->pluck('id');
dd($userID);
// $userId=Auth::user()->id;
$userSessions = $redis->smembers('users:sessions:' . $userId);
$currentSession = Session::getId();
foreach ($userSessions as $sessionId) {
if ($currentSession == $sessionId) {
continue;

}
$redis->srem('users:sessions:' . $userId, $sessionId);
$redis->del('laravel:' . $sessionId);

}
Auth::logout();
return redirect()->route('main');
}

Answer

Directly from the docs:

Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProfileController extends Controller
{
    /**
     * Update the user's profile.
     *
     * @param  Request  $request
     * @return Response
     */
    public function updateProfile(Request $request)
    {
        if ($request->user()) {
            // $request->user() returns an instance of the authenticated user...
        }
    }
}

So, it would be something like this to get the ID:

$user = $request->user();

if ($user) {
    $userID = $user->id;
}
Comments