Laravel get user id in unprotected route

1.6k Views Asked by At

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', 'ProfileController@details');
});

Route::post('search', 'searchController@search');

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

2

There are 2 best solutions below

4
On BEST ANSWER

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

Route::middleware('auth:agent')->group(function () {
    Route::get('userdata', 'ProfileController@userdata'); // 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();
6
On

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('/', 'HomeController@index')->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.