how to get data from External API url - laravel

I am using laravel v5.8.17 and i got this code from this side somewhere but my code is not working properly , i can only get status code 200 but cannot be return the response (body and header) , I tried like this : (at controller)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
class yourController extends Controller
{
public function saveApiData(){
if(isset($_res['https://my_api_url'])){
require './vendor/autoload.php';
$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'https://my_api_url', [
'formData' => [
'email' => 'myemail',
'password' => 'mypassword',
] ]);
echo $res->getStatusCode();
//200
echo $res->getHeader('content-type');
//'application/json; charset=utf8'
echo $res->getBody();
// "type":"User"...'
}
}
}

try to make it like this:
print_r(json_decode($response->getBody()->getContents()));exit(0);

Related

How set uploaded avatar in this.$page.props.user with inertiajs?

In Laravel 8 app with inertiajs/inertia-vue 0.7/vuejs2 with fortify (but without jetstream)
I use "spatie/laravel-medialibrary": "^9.9" for avatar uploading like
$loggedUser = auth()->user();
$avatar_file_path = $avatarImageUploadedFile->getPathName();
$loggedUser->addMedia( $avatar_file_path )->toMediaCollection('avatar');
and it works, but in which way can I use avatar in on client part when I use
this.$page.props.user
in vue components properties to check which user is logged and show his info?
Thanks!
You can do this with the 'Shared data' feature via the HandleInertiaRequests middleware.
For example, to share user info you can do the following:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
class HandleInertiaRequests extends Middleware
{
public function share(Request $request)
{
return array_merge(parent::share($request), [
'user' => function () {
return Auth::user() ? [
'id' => Auth::user()->id,
'name' => Auth::user()->name,
'email' => Auth::user()->email,
// get path to avatar
'avatar' => Storage::url('avatar-of-the-user.jpg'),
] : null;
},
]);
}
}
Client side you can then access the avatar's URL with this.$page.props.user.avatar.

Why users credentials are not working in my login unit testing?

I'm using PHPUnit for testing my Laravel project.
?php
namespace Tests\Feature;
use App\Models\User;
use Tests\TestCase;
class LoginTest extends TestCase
{
public function test_user_can_login():
{
$user = User::factory()->create();
$response = $this->postJson('/api/auth/login', [
'email' => $user->email,
'password' => $user->password,
]);
$response
->assertStatus(200)
->assertHeader('Authorization')
->assertJson([
'success' => 'Usuário logado com sucesso!',
]);
}
}
I want to create a new user for login test flow, but it returns a 400 status response.
Tests\Feature\LoginTest > user can login
Expected status code 200 but received 400.
Failed asserting that 200 is identical to 400.
I have no idea what is going wrong. Any suggestions?

How to fetch Rapidapi in laravel Controller?

I am trying to fetch API using unirest in my laravel application. I followed all the steps given in the docs but it's showing me an error. If there is a better alternative for unirest please let me know. Thanks in advance!
Here is my controller,
public function store(Request $request)
{
Love::create(
request()->validate([
'name_1' => ['required','max:255'],
'name_2' => ['required','max:255'],
],
[
'name_1.required' => 'You have to Enter Your name',
'name_2.required' => 'You have to Enter Your Crush name'
]));
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::post("API_URL",
array(
"X-RapidAPI-Key" => "API_KEY"
)
);
dd($response);
return view("result");
}
Error
Class 'App\Http\Controllers\Unirest\Request' not found
You need to import the Unirest\Request class.
<?php
namespace Your\Namespace;
use Unirest\Request;
class YourClass{
...
If you don't import it, it will by default look for the class in the current namespace (in your case, App\Http\Controllers).

Passing return data to another function in same controller laravel

Try to connect to external API.
In first function, I already received token with authentication.
To send POST request, I need to put xtoken that I received from first function as second function.
I don't know how to send value to second function (registerUser)
Route::get('/connect', 'Guzzlecontroller#registerUser')->name('registeruser');
this is my route file
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use App\Http\Controllers\Auth\RegisterController;
class GuzzleController extends Controller
{
public function Gettoken()
{
$client = new \GuzzleHttp\Client();
$request = $client->get(
'http://api01.oriental-game.com:8085/token',
[
'headers' => [
'X-Operator' => 'mog189b',
'X-key' => 'sQxAVNaEMe0TCHhU',
]
]
);
$response = $request->getBody();
$tokenReturn = json_decode($response, true);
$xtoken = array("x-token:" . $tokenReturn['data']['token'],);
$this->registerUser($xtoken);
}
public function registerUser($xtoken)
{
$client = new \GuzzleHttp\Client();
$url = "http://api01.oriental-game.com:8085/register";
$request = $client->post($url, [
'headers' => $xtoken,
'body' => [
'username' => 'test1',
'country' => 'Korea',
'fullname' => 'test user1',
'language' => 'kr',
'email' => 'testuser1#test.com',
]
]);
$response = $request->send();
dd($response);
}
}
Too few arguments to function App\Http\Controllers\GuzzleController::registerUser(), 0 passed and exactly 1 expected
this is error I am getting.
please help me to how to send $xtoken value to registerUser function
The problem is Laravel is calling registerUser directly instead of going through getToken. So the token is never retrieved and passed to the register action.
Instead of calling registerUser() from Gettoken(). Have Gettoken() return the token and call it from registerUser()
public function Gettoken()
{
...
return $xtoken;
}
public function registerUser()
{
$xtoken = $this->Gettoken();
...
}

How can I return two times back in Laravel 4.2?

Which classes to use for caching certain token or url? After login, I want the user to redirect two urls back in Laravel 4.2? I have tried already with URlGenerator and Request class in my User authentification function so I could catch my previous url which is GET request for login, while the desired url is before this request.
My login function:
namespace \Users\Repositories;
use View , Input , Redirect , Config;
use Illuminate\Routing\UrlGenerator;
use Users\Repositories\Contracts\AuthRepositoryInterface;
use Illuminate\Support\MessageBag;
use Illuminate\Http\Request;
class AuthRepository implements AuthRepositoryInterface {
private $messageBag;
private $errors;
private $urlGenerator;
private $request;
public function __construct(MessageBag $messageBag, UrlGenerator $urlGenerator, Request $request) {
$this->messageBag = $messageBag;
$this->urlGenerator = $urlGenerator;
$this->request = $request;
}
public function postLogin() {
$remember_me = (Input::get('remember_me') == 1 ? true : false);
try
{
// Login credentials
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
);
// Authenticate the user
$user = \Sentry::authenticate($credentials, $remember_me);
// giving example
//if(token or url)
//redirect to 'frontend.fee.registration'
//else
return Redirect::route('profile')->with('success' , trans('users::success.login_success'));
}
My routes:
Route::get( '/login' , array( 'as' => 'login' , 'uses' => 'HomeController#userLogin' ) );
Route::post('/login' , array( 'as' => 'postLogin' , 'uses' => '\Users\Controllers\AuthController#postLogin' ) );
Redirect destination:
Route::get('/fee/{id}/register/' , array( 'as' => 'frontend.fee.registration' , 'uses' => 'FeeController#feeRegistration' ) );
There is no built in solution, but you can use session to save current URLs and then use them to go back 2-3-4 etc pages back.
Look at the answer and the code here: How to return back twice in Laravel?

Resources