Home > Back-end >  how to retrieve user info using laravel auth sanctum API
how to retrieve user info using laravel auth sanctum API

Time:10-01

I'm currently developing a mobile apps for my web based system. I'm using laravel as my API . Currently, I want to do where when User A login, it will only shown User A info. How can I achieve that ? This is my AuthController where it generate my tokens.

  public function login(Request $request)
    {
        try {
            $validateUser = Validator::make($request->all(), 
            [
                'username' => 'required',
                'password' => 'required'
            ]);

            if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                    'message' => 'validation error',
                    'errors' => $validateUser->errors()
                ], 401);
            }
          
            $user = UserRegister::where('username', $request->username)->first();
      
              if(!$user || !Hash::check($request['password'], $user->password)) {
                return response([
                    'message' => 'Username & Password does not match'
                ], 401);
        }
    
             return response()->json([
                'status' => true,
                'message' => 'User Logged In Successfully',
                'user' => $user,
                'token' => $user->createToken("remember_token")->plainTextToken
            ], 200);

        } catch (\Throwable $th) {
            return response()->json([
                'status' => false,
                'message' => $th->getMessage()
            ], 500);
        }
    }

This is my api routes

Route::post('/login', [AuthController::class, 'login']);


// Homepage routes
Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::post('/logout', [AuthController::class, 'logout']);

    Route::get('/technician', [HomepageController::class, 'technician']);
});

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

and this is my HomepageController where I tried to retrieve user A data only but it does not work.

public function technician()
{
    $technician=JobRegister::where('job_assign', auth()->user()->name);
    return response()->json($technician);
}

This is my query for web based system.

$query = "SELECT * FROM job_register WHERE job_assign ='{$_SESSION['username']}'"

i want to make user A can only look at their job details that been assign. do you have any idea how to do it ? your help is much appreciated. thank you.

CodePudding user response:

try this

$username=Auth()->user()->userName  //this will return you username of logged in user
$query = "SELECT * FROM job_register WHERE job_assign ='$username'"

don't forget to use auth namespace top of in your controller like this

use Auth;
  • Related