get HTTP code in json response in laravel - php

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;

Related

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);
}
}
}

Lumen does send 204 response

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);

Symfony: type error when using flash bag in controller

In order to get the flash bag of the session and add a flash message, in the controller I call:
$request->getSession()->getFlashBag()->addFlash(...);
(where $request is an instance of Request)
but I get the following IDE type error:
Method 'getFlashBag' not found in
null|\Symfony\Component\HttpFoundation\Session\SessionInterface
The problem is that $request->getSession() returns a SessionInterface, which does not contain the getFlashBag method.
That's why the IDE is complaining, even if the actual object returned by that method is an instance of the Session class which has the getFlashBag method.
When inside a controller, a quick solution can just be using:
$this->addFlash(...);
instead of:
$request->getSession()->getFlashBag()->addFlash(...);

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 Error: The Response content must be a string or object implementing __toString(), "boolean" given

I am receiving the above error in following code and totally unable to find out real cause.
if ($validation->fails()) {
// if it fails...
return Redirect::to("login")->withErrors($validation)->withInput();
} else {
// storing user session... if it passes...
$username = Input::get("username");
Session::put("username", $username);
return Redirect::to("/");
}
Check out filters.php, make sure thar Closure return null or no returns when it passes validation.
Looks like you are authenticating users. Why not use Laravel's authentication that is offered to you out of box?
For you code, not sure if it's the chained withInput() causing the error, anyway I am strongly against chaining withErrors and withInput, for it will be problematic. A better approach is to use
Input::flash();
See the doc

Categories