Home » Php » php – Laravel get user id in unprotected route

php – Laravel get user id in unprotected route

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am using Laravel guard to to protect routes, now I want to get user id in unprotected (common) routes, for example:

Protected:

/Profile

Unprotected:

/Search

I able to get user id in protected routes, for example ProfileController.php, like this:

$id = auth()->guard('agent')->user()->id;

But I want to get this in searchController.php but it return null, any idea?

api.php:

Route::middleware('auth:agent')->group(function () {
    Route::get('profile', '[email protected]');
});

Route::post('search', '[email protected]');

In other hand, when user is logged, and open search page, I want to get user id.

How to&Answers:

You should create a controller that pass user data such id or etc:

Route::middleware('auth:agent')->group(function () {
    Route::get('userdata', '[email protected]'); // return user id
});

And:

public function userdata(){
   ...
   $id = auth()->guard('agent')->user()->id; // just id
   return $id;
}

This controller can fetch all user data, now you should need to call this request in your search controller:

app('App\Http\Controllers\ProfileController')->userdata();

Answer:

So continuing from my comments above – here’s what I tried and works without any glitch:

config/auth.php

'guards' => [
    //..

    'agent' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    //...
],

app/Http/Controllers/HomeController.php

public function index(): JsonResponse
{
    return new JsonResponse([
        'user' => auth()->guard('agent')->user(),
    ]);
}

routes/web.php

Route::get('/', '[email protected]')->name('home');

tests/Feature/HomeTest.php

/**
 * @test
 */
public function returns_user()
{
    $this->actingAs($user = factory(User::class)->create(), 'agent');

    $this->assertTrue($user->exists);
    $this->assertAuthenticatedAs($user, 'agent');

    $response = $this->get(route('home'));

    $response->assertExactJson([
        'user_id' => $user->toArray()
    ]);
}

/**
 * @test
 */
public function does_not_return_user_for_non_agent_guard()
{
    $this->actingAs($user = factory(User::class)->create(), 'web');

    $this->assertTrue($user->exists);
    $this->assertAuthenticatedAs($user, 'web');

    $response = $this->get(route('home'));

    $response->assertExactJson([
        'user_id' => null
    ]);
}

And the test passes just fine so I can only guess that there’s either something with your implementation of the agent guard or the auth:agent middleware.