In my controller i have this function
public function GetStatusDetails()
{
$response = Http::get('https://exemple.exemple.com/fr/api/<token>/availability/<Id>/getStatusDetails?format=json');
$StatusDetails = json_decode($response->body(), true);
//dd($data);
return view('ControlmAPI.netvigie', [
'StatusDetails' => $StatusDetails
]);
}
public function GetStatus()
{
$response = Http::get('https://exemple.exemple.com/fr/api/<token>/availability/<Id>/getStatus?format=json');
$Status = json_decode($response->body(), true);
//dd($data);
return view('ControlmAPI.netvigie', [
'Status' => $Status
]);
}
Is not the same call api but when i want to use StatusDetails in my blade i can't but Status i can so my question is how to pass multiple data to my blade and use it separately.
the dd of them is DD so in my blade i do {{$Status[0]['status']}} it work but when i want to do for "StatusDetails" it doesn't but if i do only for "StatusDetails" it works but not for both someone have the solution please ?
You can simply pass them as an array
public function GetStatus()
{
$statusResponse = Http::get('https://exemple.exemple.com/fr/api/<token>/availability/<Id>/getStatus?format=json');
$statusDetailsResponse = Http::get('https://exemple.exemple.com/fr/api/<token>/availability/<Id>/getStatusDetails?format=json');
$Status = json_decode($statusResponse->body(), true);
$StatusDetails = json_decode($statusDetailsResponse->body(), true);
return view('ControlmAPI.netvigie', [
'Status' => $Status,
'StatusDetails' => $StatusDetails,
]);
}
Related
A 302 error is returned when I'm trying to post to API Route, only in the second Post, using the function insereTelefone. When I'm using the Postman, it's working properly, so I think the problem is with Route, but I don't know what. I'm a newbie at the Laravel, so I'm learning how to implement things.
Here is the controller who calls the POST API:
class IndexClientes extends Controller
{
public function index()
{
$request = Request::create('/api/clientes', 'GET');
$response = Route::dispatch($request);
$clientes = json_decode($response->getContent(), true);
return view('index', compact('clientes'));
}
public function create()
{
return view('formulariocliente');
}
public function store(Request $request)
{
$nome = $request->nome;
$cpf = $request->cpf;
$email = $request->email;
$numerosTelefone = $request->telefone;
$tiposTelefone = $request->tipoTelefone;
$request = Request::create('/api/clientes', 'POST', array(
"nome" => $nome,
"cpf" => $cpf,
"email" => $email
));
$responseInicial = Route::dispatch($request);
$response = json_decode($responseInicial->getContent(), true);
$status = json_decode($responseInicial->status(), true);
if ($status !== 200) :
echo "ERRO";
die();
endif;
$idCliente = $response['id'];
if (!empty($numerosTelefone)) :
$i = 0;
foreach ($numerosTelefone as $numeroTelefone) :
$tipoTelefone = (int)$tiposTelefone[$i];
$numeroTelefone = (int)$numeroTelefone;
if (!empty($tipoTelefone) && !empty($numeroTelefone)) :
return self::insereTelefone($idCliente, $tipoTelefone, $numeroTelefone);
endif;
$i++;
endforeach;
endif;
}
public function insereTelefone($idCliente, $tipoTelefone, $numTelefone)
{
$array = array(
"cliente_id" => $idCliente,
"telefone_tipo_id" => $tipoTelefone,
"numero" => $tipoTelefone
);
$request = Request::create('api/telefones', 'POST', $array);
$responseInicial = Route::dispatch($request);
$response = json_decode($responseInicial->getContent(), true);
$status = json_decode($responseInicial->status(), true);
return $status;
}
}
TelefonesController.php
public function store(Request $request)
{
$request->validate(
[
'cliente_id' => 'required',
'telefone_tipo_id' => 'required',
'numero' => 'required|max:11'
]
);
}
api.php
Route::apiResource('telefones', \App\Http\Controllers\TelefonesController::class);
A 302 response usually means your request is being redirected by laravel.
If you are expecting a json response, you need to set the Accept: 'application/json' header along with your request just after the line:
$request = Request::create('api/telefones', 'POST', $array );
$request->headers->set('Accept', 'application/json');
the first
Route::dispatch
was redirecting the page, when I'm was trying to run the second Route::dispatch Laravel returns 302, to solve this I'm using the
app()->handle()
in the function insereTelefone to back to handle the request.
public function insereTelefone($idCliente, $tipoTelefone, $numTelefone) {
$array = array(
"cliente_id" => $idCliente,
"telefone_tipo_id" => $tipoTelefone,
"numero" => $numTelefone
);
$request_telefone = Request::create('api/telefones', 'POST', $array );
$responseInicial = app()->handle($request_telefone);
$status = json_decode($responseInicial->status(),true);
return $status;
}
How can we be able to get a status code response if we are not able to pass the data on the api? I need your help guys I am completely new on this. Thanks in advance.
contoller
...
public function user(Request $request) {
$params = [
"firstName" => $request->firstname,
"lastName" => $request->lastname,
];
return $this->VoucherFactory->saveUser($params);
}
...
VoucherFactory.php
...
public function saveUser($params)
{
return $this->HttpClient->makeRequestPost($params, 'api/users', true);
//status code response logic
}
...
I'd do smth like this:
In the factory:
public function saveUser($params)
{
// No params passed, set code to 400
if(empty($params)) {
$statusCode = 400;
} else {
// Params passed, try to save user
$saveUserResult = $this->HttpClient->makeRequestPost($params, 'api/users', true);
// User saved ok
if($saveUserResult) {
$statusCode = 200;
} else {
$statusCode = 400;
}
}
return ["code" => $statusCode];
}
And than in the controller:
public function user(Request $request) {
$params = [
"firstName" => $request->firstname,
"lastName" => $request->lastname,
];
$result = $this->VoucherFactory->saveUser($params);
return $result["code"];
// Or if using some kind of framework, smth like:
// return $this->view(null, $result["code"]);
}
in you saveUser() function,
$this->HttpClient->makeRequestPost($params, 'api/users', true);
//after
return response()->setStatusCode(Response::HTTP_OK);
or in api/users route Controller, return the desired response
I have two routes.
Route::get('/receiveSignal', 'SignalController#receiveSignal');
Route::get('/sendSignal', 'SignalController#sendSignal');
I want to simulate sending data from sendSignal to receiving signal route.
So, in sending signal function I have this:
public function sendSignal()
{
$data = ['spotid' => '421156', 'name' => 'Test', 'desc' => 'some desc', 'StartofDetection' => '2018-01-17 22:22:22'];
$dataJson = json_encode($data);
return $dataJson;
}
How can I change it to receive in receiveSignal like this:
public function receiveSignal()
{
$test = file_get_contents('php://input');
dd($test);
}
Here I should receive the json to the receiveSignal after I enter the http://localhost:8000/sendSignal. Is this possible at all?
Try something like this:
1. In your route:
Route::post('receiveSignal', 'SignalController#receiveSignal');
Route::get('sendSignal', 'SignalController#sendSignal');
In your sendSignal method
public function sendSignal()
{
$data = ['key' => 'value', 'key2' => 'value2'];
$response = http_post_fields('http://localhost:8000/receiveSignal', $data);
if (!empty($response)) {
return view('success'); // or anything else you want to return
}
else {
return view('failed');
}
}
In your receiveSignal method
public function receiveSignal(Request $request)
{
$key = $request->input('key');
$key1 = $request->input('key2');
//and so on
}
Good luck.
I am writing some tests for my controllers but one of my tests doesn't work. It's supossed to search and get the results back to the page. But it's actually redirecting to the home page. Here is my code:
use DatabaseMigrations;
protected $user;
public function setUp()
{
parent::setUp();
$this->seed();
$this->user = factory(User::class)->create(['role_id' => 3]);
}
/** #test */
public function test_manage_search_user()
{
$response = $this->followingRedirects()->actingAs($this->user)->get('/manage/users/search', [
'choices' => 'username',
'search' => $this->user->username,
]);
$response->assertViewIs('manage.users');
$response->assertSuccessful();
$response->assertSee($this->user->email);
}
The URL you should get to make it work look like this:
http://localhost/manage/users/search?choices=username&search=Test
I checked again and it looks like it's not given in the parameters with the get request. How can I fix this?
I had the same issue trying to test GET Requests, you actually can't pass parameter with the $this->get('uri', [header]) but you can by using $this->call, if you check in MakesHttpRequests.php you can see that this->get() is actually using call method.
By adding an array to get method, you are changing the request headers, this is why you are not getting your parameters.
public function get($uri, array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
return $this->call('GET', $uri, [], [], [], $server);
}
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
$kernel = $this->app->make(HttpKernel::class);
$files = array_merge($files, $this->extractFilesFromDataArray($parameters));
$symfonyRequest = SymfonyRequest::create(
$this->prepareUrlForRequest($uri), $method, $parameters,
$cookies, $files, array_replace($this->serverVariables, $server), $content
);
$response = $kernel->handle(
$request = Request::createFromBase($symfonyRequest)
);
if ($this->followRedirects) {
$response = $this->followRedirects($response);
}
$kernel->terminate($request, $response);
return $this->createTestResponse($response);
}
So if you want to test a GET Request you will have to do this:
$request = $this->call('GET', '/myController', ["test"=>"test"]);
In your controller you should be able to get theses parameters like so:
public function myController(Request $request)
{
$requestContent = $request->all();
$parameter = $requestContent['test'];
}
I'm using Laravel 5.X (more precisely 5.6), you can pass custom parameters using:
$response = $this->json('GET', '/url/endpoint',['params'=>'value']);
You can use the route helper to build a url with query string. in your case i would do something like this. Assuming the route name is manage.users.search
$route = route('manage.users.search', [
'choices'=> 'username',
'search' => $this->user->username,
]);
$response = $this->followingRedirects()
->actingAs($this->user)
->get($route);
In order to send parameters with GET requests.
If you use the route() method then you can pass the data as the second parameter.
$response = $this->get(route('route_name', ['key' => value]));
If you using URL directly, you could use like this
$response = $this->get('url?' . Arr::query(['key' => value]));
Do whatever you want to do with $response.
You could use the request helper to merge in http get parameters as such:
/** #var \Illuminate\Http\Request $request */
$request = request();
$request->merge([
'choices' => 'username',
'search' => 'Test'
]);
This worked for me simply pass the parameter as part of the url as follows:
$response = $this->get('api/endpoint?parameter1='.$this->dynamicParam);
Add a helper function:
if (!function_exists('extend_url_with_query_data')) {
function extend_url_with_query_data(string $url, array $queryData): string
{
if ($queryData == []) {
return $url;
}
$glue = mb_strpos($url, '?') === false ? '?' : '&';
$queryString = http_build_query($queryData);
return "{$url}{$glue}{$queryString}";
}
}
Usage:
$queryData = [
'works' => true,
];
$this->get(
extend_url_with_query_data('/api/v1/example', $queryData)
);
I would do it like this:
$this->actingAs($this->user);
$response = $this->get('/manage/users/search', [
'choices' => 'username',
'search' => $this->user->username,
]);
$response->assertViewIs('manage.users');
$response->assertSuccessful();
$response->assertSee($this->user->email);
While trying to request data from en external API, I want to control how the response is being passed to my view or database. However what would be the correct way to write the code below, so instead of simply echoing the data onto the view I would like to store it inside an object that I can pass to my view or model in a more controlled way?
public function index()
{
$contents = $this->saveApiData();
return View::make('stats.index')->with('contents', $contents);
}
public function saveApiData()
{
$client = new Client(['base_uri' => 'https://owapi.net/api/v3/u/']);
$res = $client->request('GET', "data" . "/blob");
echo $res->getStatusCode();
echo $res->getBody();
}
Just put them together in an array and return it. You never echo data in a function to return them.
public function saveApiData()
{
$client = new Client(['base_uri' => 'https://owapi.net/api/v3/u/']);
$res = $client->request('GET', "data" . "/blob");
$contents = [
'status' => $res->getStatusCode(),
'body' => $res->getBody()
];
return $contents;
}