This code in Laravel where I want to use it as API to show it for every one that visit my app. and I want to get user ID when he is logged in.
public function show($displayType)
{
try {
$data = houses::where('displayType', $displayType)->paginate(5);
$user = auth()->user(); // Get the authenticated user
$userId = $user ? $user->id : null; // Check if user is authenticated and get the user ID
return response()->json([
'status' => true,
'message' => 'You have successfully retrieved data',
'data' => $data,
'user_id' => $userId, // Include the user ID in the response
]);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage(),
], 500);
}
}
I want to check if the person that visited my site is logged in or no.
But the problem is when I send token is return user id null that's how use my route request.
// this my route I use it out the middleware check
Route::get('houses/{displayType}',[housesController::class, 'show']);
Route::middleware('auth:api')->group(function () {})
Use the check()
function to verify if the user is logged in.
if (auth()->check()) {
// User is logged in
$user = auth()->user();
} else {
// User is not logged in
}
In Blade, directives are also available for simplified invocation of these functions.
@auth
// The data only available for auth user
@endauth
// and
@guest
// Show content if unauthenticated
@endguest
We can explicitly specify that only logged-in users can access routes.
Route::get('houses/{displayType}', [HousesController::class, 'show'])
->middleware('auth'); // use middleware() function to add extra middleware to route
// or can use with group() function to can add extra middleware to more route
Route::middleware('auth')->group(function () {
Route::get('houses/{displayType}', [HousesController::class, 'show']);
})
Laravel by default applies web
session-based authentication. If you want to deviate from this, you need to communicate it properly with Laravel through settings. If you want to use token-based API authentication for default login, you need to modify the defaults.guard
value appropriately in config/auth.php
as per the documentation.
return [
'defaults' => [
'guard' => 'api', // here
],
'guards' => [
// default guard
'web' => [
'driver' => 'session',
'provider' => 'users',
],
// can use this
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => true,
],
],
];
If you prefer not to modify this, you have the option to override this value in each of your requests using the guard()
function.
if (auth()->guard('api')->check()) {
// User is logged in
$user = auth()->guard('api')->user();
} else {
// User is not logged in
}