Search code examples
phplaravellaravel-guard

Laravel get user id in unprotected route


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.


Solution

  • 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();