Lumen does send 204 response - php

I have created the following function into the main Controller.
public function noContent() : JsonResponse
{
return response()->json([], Response:HTTP_NO_CONTENT);
}
When deleting some data, I am returning the above function but I get a message that "Could not get any response".
I also have tried to pass a message (even if this is not recommended for a 204) in the array but still, I receive the same error. I am using the same function to return 200 or 404 messages and there worked as expected.
Is there another solution to make this work?

You should do:
return response('', 204);

Related

Laravel Guzzle returns blank response in Get() method

I use this code to get balance from another server,
it works fine on XAMPP locally, but it doesn't on the production server, it just returns blank response page.
public static function balance(){
try {
return (string) (new \GuzzleHttp\Client())
->get("http://www.*****.ps/getbalance.php?user_name=****&user_pass=*****")
->getBody();
} catch (\Exception $e) {
return '-';
}
return '-';
}
My issue was a problem with the destination server, for some reason our server got blocked.
There is no problem in the mentioned code. It works fine.

get HTTP code in json response in laravel

I need to save the response code that was sent via json, for example 404:
Route::fallback(function(){
return response()->json(['message' => 'Not Found'], 404);
})->name('api.fallback.404');
I tried with this code:
use Illuminate\Http\JsonResponse as Resp;
if (!$this->response_code) {
$this->response_code = Resp::getStatusCode();
}
but laravel return me this error:
Non-static method Symfony\Component\HttpFoundation\Response::getStatusCode() should not be called statically
You're trying to call a non-static method (meaning, a method belonging to the object) from the Class itself. Try this:
use Illuminate\Http\JsonResponse as Resp;
if (!$this->response_code) {
$this->response_code = $this->getStatusCode();
}
Jaime's answer looks pretty good as a general solution to any error where they say it cannot be called statically, but I'm not seeing that method on the Illuminate\Http\JsonResponse object at all--hence the 500 error you reported back.
The Laravel documentation for JsonResponse indicates that you can call status() on the JsonResponse object to get the int value of the response code.
You can use http_response_code() to get the response code.
$this->response_code = http_response_code;

Laravel 5.4 login JSON error respond

I would like to make an AJAX login request, where the authentication fails, the authentication error message should be returned in a JSON object. What is the nicest way to do this?
Thanks for the answers in advance!
EDIT:
I generate the auth with the php artisan make:auth command.
There's 2 possibilities for the authentication to fail:
The request fails validation
The credentials are not valid
When the request fails validation the error returned adapts based on what the request expects so if it was JSON it will return the error in the JSON response.
The problem is for the 2nd case, in that case you can simply do:
class LoginController {
use AuthenticatesUsers {
sendFailedLoginResponse as protected traitSendFailedLoginResponse;
}
protected function sendFailedLoginResponse(Request $request) {
if ($request->expectsJson()) {
return response()->json([ "errors" => Lang::get('auth.failed') ]);
} else {
return $this->traitSendFailedLoginResponse($request);
}
}
}

Difference among return view(), return response()->view() and abort() in laravel

Suppose i want to return 404 error view from my controller's method and i have this block of code.
try {
file_get_contents('http://www.somewebsite.com');
}
catch (\Exception $e) {
return view('errors.404'); // View::make('errors.404');
// or
return response()->view('errors.404'); // Response::view('errors.404');
// or
abort(404); // App::abort(404);
}
Each time i'll see the same view output of 404. Here is my questions.
What is the difference among view(), response()->view() and abort()?
What is the particular use cases of them?
view() is just a shorthand for response()->view()
response()->view() returns the specified view with the status code 200, but you are able to modify the response in many ways. For example set other headers or another status code like 301.
abort() throws an NotFoundHttpException or HttpException and will make Laravel look for a view named like the corresponding code in views/errors so you don't have to specify the view on your own.
When you use view() or response()->view() the HTTP response code your client recieves will be 200 aka OK. When using abort(404) the code will be 404 NOT FOUND!

Laravel 4 always returns HTTP status code 200

I have below code in error.php, which is triggered using App::abort(404, $error) in my controller. Still my response status code is 200(ok). I tried with various error codes like 400, 403
// NotFoundException handler
App::error(function(NotFoundException $e)
{
$default_message = 'The requested resource was not found';
return Response::json(array(
'error' => $e->getMessage() ?: $default_message,
), 404);
});
For anyone still googling this problem:
I was struggling with this problem for hours. For me the problem was caused by an issue with one of my controllers.
Check all of your controllers and make sure there are no spaces in front of the <?php tag. The <?php tag should be the very first thing in the file. A single space in front of the <?php tag in any of your controllers that are routed as such:
Route::controller('example', 'ExampleController');
Will cause all status codes to be 200.
I believe, regardless, you should receive a 404 response, so there might be something else happening that's the result of code not included in your question.
That being said, the Exception class that is thrown for 404 is NotFoundHttpException rather than NotFoundException.
Since Laravel 4 uses Symfony's HttpKernal, that Exception is here.
You can see here where App::abort() throws NotFoundHttpException when a 404 is triggered.
Therefore, your code should look like:
// NotFoundHttpException handler
App::error(function(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e)
{
$default_message = 'The requested resource was not found';
return Response::json(array(
'error' => $e->getMessage() ?: $default_message,
), 404);
});
Important: This will only fire for a 404 status, as that's the corresponding code to NotFoundHttpException. Other status codes return other Exception classes. To capture all HTTP status error codes exceptions, type hint for HttpException like so:
// HttpException handler
App::error(function(\Symfony\Component\HttpKernel\Exception\HttpException $e)
{
return Response::json(array(
'error' => $e->getMessage(),
), $e-> getStatusCode());
});
Lastly, consider using a bit of Content Negotiation when deciding to return JSON or HTML.
The solution didn't worked for me, so in case anyone is still looking for an answer, I thought it be best to put it here instead of creating another question.
After some time I had this problem too, in my app/Exceptions/Handler.php I had:
if ($e instanceof ModelNotFoundException) {
if ($request->ajax()) {
return response()
->json(['error' => ['No results']])
->header('status', 422);
}
}
This worked in my local environment, however, in the homolog environment (which reproduces the production environment, just to be clear) it didn't returned the correct status code.
After another look I started looking at Laravel's docs, and I changed the call to the following:
return response()
->json(['error' => ['No results.']], 422);
And that did the trick. Hope this can help.
In my case I found some space in front of <?php
Remove dump & other print functions
I was actively debugging when I noticed this issue. It was caused because I had dump(...) calls in the code at that time.
When I removed all my debug dump calls, the status code was correctly 404 again (using abort(404).

Categories