How can I set a response using a var? - laravel

In the laravel docs it has:
return response($content);
What format is $content?
I want to return it via a var like so:
$res = [null, 204];
return response($res);
But the above fails, just returns a 200.
How can I set a response using a var?

response method like this. response($contents, $statusCode) It's a method of instance Response Object. as you can see that method is getting two parameters. one is contents that you are trying to return to client side. it depending what Content-Type is set in header.
so you can try like this.
$contents = "something whatever";
$statusCode = 204;
return response($contents, $statusCode);

$content can be various things - null, a string, an array.
Status codes are set via a second parameter, not an array element. Passing it an array results in a JSON response, so you're creating a 200 status JSON response of [null,204] with your code.
You fundamentally need to do:
return response(null, 204);
What you can potentially do is generate a response as a variable:
$res = response(null, 204);
and then return $res; elsewhere.

Related

Laravel GET Method not sending raw JSON in Server

Working with REST API's in Laravel. Can't send raw json request in body using GET method, it returns null values in my server environment. But in local server works fine. Refer the attached images. And my controller code was,
public function slots(Request $request)
{ //return $request->all();
$consult_rule = TRUE;
date_default_timezone_set('Asia/kolkata');
$current_time = date('H:i:s');
$curr_date = date('Y-m-d');
// $appoint_date = DateTime::createFromFormat('d/m/Y', $request->appoint_date)->format('Y-m-d');
// $appoint_date_format = strtotime($appoint_date);
// $appoint_day = date('l', $appoint_date_format);
$date = $request->appoint_date;
$doctor_id = $request->doctor_id;
$appoint_for = $request->appoint_for;
return $this->sendResponse(['doctor_id' => $doctor_id,'appoint_date' => $date,'appoint_for' => $appoint_for], 'Data retrieved successfully.');
}
And the images,
For Local server works fine
Localhost response
For Server works fine with Key Parameters
Server response with key parameters
For Server return null values with raw JSON parameters
response with raw JSON parameters
Since it is a GET route, it expects parameters in URL.
For POST request, you need to define a separate Route and function which will take parameters in body.
EDIT: you can't send parameters in body when using GET HTTP method.
Refer:
https://laravel.com/docs/7.x/routing#required-parameters

Is it possible to call method pop with callback (laravel collections)?

I have a collection that contains answers from guzzle HTTP client. The answers can be 404, 200 or 500.
I would like to pop objects form the collection that contains only 200 and 404 statuses and leave with the statuses 500. So, I would like something like:
$done = $res->pop(function ($item, $index) {
$statusCode = $item->getStatusCode();
return $statusCode === 404 || $statusCode === 200;
});
But it's impossible( Because the pop methods don't take callback. Any ideas how to make this elegantly?
I think filter would be a better solution if you still want to keep the responses with status 500 in the original array (documentation here):
$done = $res->filter(function ($item) {
return $item->getStatusCode() === 500;
});
// $done will contain only responses with 500 status code
// $res will not be touched
Otherwise you could use partition to actually split the data in two groups keeping the original array unaltered (documentation here):
list($status500, $status200_404) = $collection->partition(function ($item) {
return $item->getStatusCode() === 500;
});
// $status500 will contain only responses with 500 status code
// $status200_404 will contain only responses with 200 and 404 status code
// $res will not be touched

How i can get the variable data as string like a dd() function in Laravel?

I need to get the request data but i cant get ip, fullUrl and others with all() method (this only print input values), but when i use "dd(request())" this show me all data (i need the data what is printed with dd method, but like a string to save, withour the exception who print this data). Im debbuging my app so i need to save every request data in a log file, something like:
\Log::debug($request)
So,
You can use:
\Log::debug($request->toString());
or alternatively you can use
\Log::debug((string) $request);
The Laravel Request object comes from Illuminate\Http\Request which extends Symfony\Component\HttpFoundation which exposes the following code:
public function __toString()
{
try {
$content = $this->getContent();
} catch (\LogicException $e) {
return trigger_error($e, E_USER_ERROR);
}
$cookieHeader = '';
$cookies = [];
foreach ($this->cookies as $k => $v) {
$cookies[] = $k.'='.$v;
}
if (!empty($cookies)) {
$cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
}
return
sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
$this->headers.
$cookieHeader."\r\n".
$content;
}
__toString() is considered a magic method in PHP.
The __toString() method allows a class to decide how it will react
when it is treated like a string. For example, what echo $obj; will
print. This method must return a string, as otherwise a fatal
E_RECOVERABLE_ERROR level error is emitted.
You can read more about it in the official documentation.
I highly recommend to store just what you want from request data if you don't need all of them, however for both cases you can take a look at serialize and json_encode

Laravel $request with variable returns null

I am writing an update methoda for my api. I neede to update requested fields.
So ı am trying to get only requested fields and update them. However, the code below returns me null even thoug I cast $fill to string.
foreach ($fillableFields as $fill){
$customerId->$fill = $request->get("$fill") ;
edit- 1
My code is like below ;
$fillableFields = array('lastname','firstname');
when I dd($fill) it returns me null .
You forgot to call the save() method to update your object :
foreach ($fillableFields as $fill){
$customerId->$fill = $request->get($fill);
$customerId->save();
}
Your method should be.
public function yourMethod(Request $request)
{
try {
foreach ($fillableFields as $fill){
$customerId->$fill = $request->get($fill) ;
}
}
} catch (\Exception $ex) {
}
}
Best way to get request parameters is provided at laravel's official documentation as below.
You can get request parameter based on your specific need.
By using below statment you can get only those perameter you have specified in only attribute as array eg : username, password.
$input = $request->only(['username', 'password']);
If you wantto get all fields excluding particular field than you can define as below with except parameter. eg: by using below it will allow to get all the fields except credit_card.
$input = $request->except('credit_card');
For more information on request parameter please refer official doc url : https://laravel.com/docs/5.4/requests

Appending to Response::json() from App::after after returning from my controller

I have route, then it will call function from my controller, in my controller, I am returning using return Response::json(array); , now, I have App::after which i want to append something to the current Response returned by my controller, is there any way to get the current response inside App::after filter?
I found out that i can get the current response by simply using:
$return = json_decode($response->getContent());
$return->hasLogout = true; // Appended new response data
$response->setContent(json_encode($return));

Resources