How To Get Current Logged in User Data in React Native Using Laravel Auth Sanctum API

Viewed 41

I am using Laravel API as a backend for my react-native application. I want to get all the logged in user's data from the users table when he logs in.

I've tried several things but nothing has worked so far.

Here is my code:

Laravel api.php:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});// i also tried this code.


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

ProfileScreen.js

 const [user, setUser] = useState({});

  const getUser = async () => {
    try {
      const token = await AsyncStorage.getItem('auth_token');
      axios.get("/api/user").then(res => {
        console.log(res.data)//this is logging nothing.
       
      }).catch(e => console.log(e));
    } catch (e) {
      console.log('error' + e);
    }
  };

  useEffect(() => {
    getUser();
  });
1 Answers

auth()->user() is a global helper, Auth::user() is a support facade, and $request->user() uses http.

You can use any of them. For a quick test, try

Route::get('/test', function() {
    return auth()->user();
})->middleware('auth:sanctum');

Be sure to send your token in a header like so:

 Authorization: Bearer UserTokenHere
Related