whats the response ie dd($response).. plus you might have CSRF issue in the API so make sure you have some exceptions in VerifyCSRF token middleware in the api
Aug 30, 2020
2
Level 1
how to post form data through guzzle in api
I created an API for login in laravel. In postman it is working properly. Now I want to use that api from my web form. I have an login form and fill email and password then click on button then my login api should be run and should be redirect on dashboard.
For this I am using GUZZLE.
API is (in, routes/api.php):
Route::post('login', 'apifolder\AuthController@login');
login method in AuthCOntroller is:
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
}
Above API is working properly in postman.
Now I want to use it from my web form.
routes are(in, routes/web.php):
Route::get('/','loginController@index')->name('login');
Route::POST('/login','loginController@login_submit')->name('login.submit');
controller is:
public function login_submit(Request $request)
{
$client = new \GuzzleHttp\Client();
$url = "http://127.0.0.1:8000/api/auth/login";
$body['form_param'] = array('email'=>$request->email,'password'=>$request->password);
$request = $client->post($url,$body);
$response = $request->send();
dd($response);
}
login blade is:
<form action="{{ route('login.submit') }}" method="post">
@csrf
<div class="input-group mb-3">
<input type="email" class="form-control" name="email" placeholder="Email">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input type="password" class="form-control" name="password" placeholder="Password">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="row">
<!-- /.col -->
<div class="col-4">
<button type="submit" class="btn btn-primary btn-block">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
But not working.
Please or to participate in this conversation.