I can see you return json in every case. So, the best way to handle that is taking care of the redirects in Js and set the authenticated user details in you root component state.
What is the proper way to handle API redirection
Hey guys, I am working on a project that uses React for the frontend and Laravel for the API endpoints which I am responsible for.
The logic is to redirect users to the dashboard on successful registration or login. The dashboard will be displaying all user info except the password of course.
Here's how I have setup the registration and login API endpoints using Passport
api.php
Route::post('register', 'BaseController@register');
Route::post('login', 'BaseController@login)
My BaseController methods are set up like this
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'firstname' => 'required',
'lastname' => 'required',
'username' => 'required|email',
'password' => 'required'
]);
if ($validator->fails()) {
return response()->json(['Error', $validator->errors()], 401);
}
$user = User::create([
'firstname' => $request->firstname,
'lastname' => $request->lastname,
'username' => $request->username,
'password' => bcrypt($request->password)
]);
$success['token'] = $user->createToken('Pramopro')->accessToken;
return response()->json(['success' => $success, 'message' => 'You have successfully registered'], 200);
}
public function login() {
if (Auth::attempt(['username' => request('username'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('Pramopro')->accessToken;
return response()->json(['success' => $success, 'message' => 'You have succesfully signed in.'], 200);
}
else
{
return response()->json(['error' => 'Unauthorised'], 401);
}
}
Both endpoints work fine and i get the token back.
My question is how do I set up the dashboard API so that on redirect the authenticated user details are sent in the response?
Please or to participate in this conversation.