Home > Blockchain >  Login using external API in laravel
Login using external API in laravel

Time:12-20

Curently i tried to login using username and password from external api https://fakestoreapi.com/auth/login with HTTP client that if login success will recevie a token.

Now i have to make a error message and return back 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.

CodePudding user response:

maybe you can use GuzzleHttp\Client when you execute post method.

for example using guzzlehttp below :

use GuzzleHttp\Client;

    public function PostData(Request $request)
    {
        $client = new Client();
        $username = $request->username;
        $password = $request->password;
            $url = 'https://yoururl.example'

        $params = [
            "username" => $username,
            "password" => $password
        ];

        $response = $client->request('POST', $url, [
            'json' => $params
        ]);

        return json_decode($response->getBody());
    }

Then you can dump & die / dd the response->getBody() for get output

CodePudding user response:

You are attempting to json_decode the entire $response object which will fail. There is easier way get this done:

Gets an array of all response data:

$data = $response->json();

To get just the token:

$token = $response->json('token')
  • Related