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.
Related
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,
]);
}
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
public function addcategory() {
$this->load->model('product_model');
$new_category = $this->product_model->add_category($this->input->post());
if ($new_category) {
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
$this->index($info);//not working
}
$this->index($info);//working without $info
}
here i need to call $this->index($info); within the if(){} but it is not working... however when i put this code outside if() it works but i cant pass $info variable via $this->index($info);
I call the function($this->index($info);) in side if then function not working at all. But if i used function outside if its get call but giving an error 'Undefined index: info'.
How to call the index() function??
Declare $info outside the if statement should work.
Then use the index function outside the statement.
public function addcategory() {
$info = null;
$this->load->model('product_model');
$new_category = $this->product_model->add_category($this->input->post());
if ($new_category) {
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
}
$this->index($info);//working without $info
}
Solution1:
You can use Redirect method to redirect on index :
$this->session->set_flashdata('info', $info);
redirect('/controller_name/index');
And get the info on index method :
$info = $this->session->flashdata('info');
Solution2:
Add this Remap Function to your controller :
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->index();
}
}
Your if statement is not doing anything with the variable $new_category
try.
if (isset($new_category) && !empty($new_category)) // check for the existence and value
{
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
$this->index($info);
}
else
{
$info = array(
'message' => 'unsuccessful data entry',
'value' => FALSE
);
}
I am looking for a way to access and change the DATABASE_CONFIG variables, based on user input. Using CakePHP I created a custom datasource, based on the one provided in the docs, to access an external API. The API returns a JSON string containing the 12 most recent objects. I need to be able to change the page number in the API request to get the next 12 results, as well as accept a free text query entered by the user.
app/Config/Database.php
class DATABASE_CONFIG {
public $behance = array(
'datasource' => 'BehanceDatasource',
'api_key' => '123456789',
'page' => '1',
'text_query' => 'foo'
);
}
app/Model/Datasource/BehanceDataSource.php
App::uses('HttpSocket', 'Network/Http');
class BehanceDatasource extends DataSource {
public $description = 'Beehance datasource';
public $config = array(
'api_key' => '',
'page' => '',
'text_query' => ''
);
public function __construct($config) {
parent::__construct($config);
$this->Http = new HttpSocket();
}
public function listSources($data = null) {
return null;
}
public function describe($model) {
return $this->_schema;
}
public function calculate(Model $model, $func, $params = array()) {
return 'COUNT';
}
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] === 'COUNT') {
return array(array(array('count' => 1)));
}
$queryData['conditions']['api_key'] = $this->config['api_key'];
$queryData['conditions']['page'] = $this->config['page'];
$queryData['conditions']['page'] = $this->config['text_query'];
$json = $this->Http->get('http://www.behance.net/v2/projects', $queryData['conditions']);
$res = json_decode($json, true);
if (is_null($res)) {
$error = json_last_error();
throw new CakeException($error);
}
return array($model->alias => $res);
}
}
Is there anyway to access and change the $behance array, or is there another way to go about accessing an external API with cakePHP that I am totally missing?