1

I need to convert a Laravel Edit Profile form page to React (Partially), I am using react-hook-form for the Edit Profile page form, the form has an onsubmit ajax call ( POST api/v1/user/profile/edit ) that needs to be authorized with the authorization header with access token, the access token is generated by Laravel Passport like:

    public function login( LoginRequest $request )
    {
        // Parameter(s)
        $data = [
            'email'             => $request->email,
            'password'          => $request->password,
        ];

        // Login & Return User Model
        $user = $this->users->login( $data );

        // Create + Get Access Token
        $access_token = $user->createToken('user_access_token', [])
            ->accessToken;

        // Transform Result
        $result = $this->loginTransformer->transform( $user );

        // RETURN Result
        return $this->sendResponse($result, trans('api.user.login_success'))
            ->header('Authorization', 'Bearer '.$access_token);

How do I pass the Laravel Passport access token from Laravel to the frontend React component?

yelnn
  • 73
  • 7
  • your question should be edited. if you're asking a React question you don't need to mention Laravel code. if you have a question about Laravel then you should remove React tag and name or ask it in another question separately. but if I understood correctly: you should send AccessToken through the body of the login request in the Laravel and then when you got it in the front-end, you should add AccessToken in header of all request in Bearer structure. – Amir Mohammad Moradi Feb 20 '21 at 07:31
  • hi, thanks for the reply, I am confused and need to know how the flow works, For the login of the website, I am using the Laravel 'web,auth' middleware, instead of `auth:api`, do I need to convert all the frontend to backend request to use API instead? – yelnn Feb 20 '21 at 07:49
  • then. it is better we go forward step by step. first of all, we should check and fix your backend. does your backend communicate with RESTful APIs? – Amir Mohammad Moradi Feb 20 '21 at 07:51
  • my Laravel backend mostly communicate with the `web.auth` middleware instead of `auth:api`, so most of it use CSRF/session, should all the backend-to-frontend communication be switched to stateless `API` communication instead? – yelnn Feb 20 '21 at 08:26
  • I don't know Laravel a lot, but if your auth scenario isn't using APIs but instead using session, then you can use cookies in front-end. but I think it is better to deal with APIs – Amir Mohammad Moradi Feb 20 '21 at 08:48
  • I see, so if I use `API` for the `/login` request and after login success and it returned the `access token` to the frontend, how should I store it for later use? and how to use it for subsequent API request? – yelnn Feb 20 '21 at 09:02

0 Answers0