Currently I tried to login using username and password from external API https://fakestoreapi.com/auth/login with HTTP client that if login success will receive a token.
Now I have to make an error message and return to login form if username and password wrong. But what I get still an error from laravel like Attempt to read property "token" on null. Please help me, I'm a beginner.
This is my controller code.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
class MasukController extends Controller
{
public function masuk()
{
return view('login');
}
public function cek(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required',
]);
// Send a POST request to the API
$response = Http::post('https://fakestoreapi.com/auth/login', [
'username' => $request->input('username'),
'password' => $request->input('password'),
]);
// Decode the response
$data = json_decode($response);
// Get the token from the response
$token = $data->token;
// Redirect to the dashboard page
if (is_null($token)) {
Session::flash('error', 'Error: Token is null');
// Redirect the user back to the previous page
return redirect()->back();
} else {
session(['token' => $token]);
return redirect('/');
}
}
}
I want to show error message if username and password not match in login form.
$responsereturn something.you can usedd($response)