Laravel 5 : How to use findOrFail() method? - php

I just follow some tutorial and so far what I do is :
my App/Exceptions/Handler.php
<?php
...
use Illuminate\Database\Eloquent\ModelNotFoundException;
...
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException){
abort(404);
}
return parent::render($request, $e);
}
and my UsersController looks like this :
...
public function edit($id)
{
$data = User::findOrFail($id);
$roles = Role::where('title', '!=', 'Super Admin')->get();
return View('admin.user.edit', compact(['data', 'roles']));
}
...
with the above code if I visit http://my.url/users/10/edit I get NotFoundHttpException in Application.php line 901:, yes because there is no id 10 in my record, but with User::find($id); I get normal view without data, since no id 10 in my record.
What I want is show default 404 then redirect to somewhere or return something if record not found with User::findOrFail($id); ? How I can do that ?
Thanks, any help appreciated.
ps: .env APP_DEBUG = true

This does what you asked. No need for exceptions.
public function edit($id)
{
$data = User::find($id);
if ($data == null) {
// User not found, show 404 or whatever you want to do
// example:
return View('admin.user.notFound', [], 404);
} else {
$roles = Role::where('title', '!=', 'Super Admin')->get();
return View('admin.user.edit', compact(['data', 'roles']));
}
}
Your exception handler is not necessary as it is. Regarding Illuminate\Database\Eloquent\ModelNotFoundException:
If the exception is not caught, a 404 HTTP response is automatically sent back to the user, so it is not necessary to write explicit checks to return 404 responses when using [findOrFail()].
Also, I'm pretty sure you get the exception page instead of 404 now because you're in debug mode.

public function singleUser($id)
{
try {
$user= User::FindOrFail($id);
return response()->json(['user'=>user], 200);
} catch (\Exception $e) {
return response()->json(['message'=>'user not found!'], 404);
}
}

findOrFail() is alike of find() function with one extra ability - to throws the Not Found Exceptions
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
Its not recommended but If still you want to handle this exception globally, following are the changes as per your handle.php
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
//redirect to errors.custom view page
return response()->view('errors.custom', [], 404);
}
return parent::render($request, $exception);
}

Late addition to above topic: If you want to handle the exception for an API backend and you don't want to make the check for an empty result in each method and return a 400 Bad request error individually like this...
public function open($ingredient_id){
$ingredient = Ingredient::find($ingredient_id);
if(!$ingredient){
return response()->json(['error' => 1, 'message' => 'Unable to find Ingredient with ID '. $ingredient_id], 400);
}
return $ingredient;
}
Instead use findOrFailand catch exception in app/Exceptions/Handler.php.
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
return response()->json(['error'=>1,'message'=> 'ModelNotFoundException handled for API' ], 400);
}
return parent::render($request, $exception);
}
This will then look like this in your Controllers:
public function open($ingredient_id){
return Ingredient::findOrFail($ingredient_id);
}
which is much cleaner. Consider that you have plenty of Models and plenty of Controllers.

Related

render function in Handler.php not working Laravel 8

I want to return a JSON response instead of the default 404 error page when ModelNotFoundException occurs. To do this, I wrote the following code into app\Exceptions\Handler.php :
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'error' => 'Resource not found'
], 404);
}
return parent::render($request, $exception);
}
However it doesn't work. When the ModelNotFoundException occurs, Laravel just shows a blank page. I find out that even declaring an empty render function in Handler.php makes Laravel display a blank page on ModelNotFoundException.
How can I fix this so it can return JSON/execute the logic inside the overriden render function?
In Laravel 8x, You need to Rendering Exceptions in register() method
use App\Exceptions\CustomException;
/**
* Register the exception handling callbacks for the application.
*
* #return void
*/
public function register()
{
$this->renderable(function (CustomException $e, $request) {
return response()->view('errors.custom', [], 500);
});
}
For ModelNotFoundException you can do it as below.
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
return response()->json(...);
});
}
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering Closure for exceptions of a given type. You may accomplish this via the renderable method of your exception handler. Laravel will deduce what type of exception the Closure renders by examining the type-hint of the Closure:
More info about the error exception
This code doesn't work for me (in Laravel 8.74.0):
$this->renderable(function (ModelNotFoundException$e, $request) {
return response()->json(...);
});
Don't know why, but ModelNotFoundException is directly forwarded to NotFoundHttpException (which is a part of Symfony Component) that used by Laravel and will ultimately triggers a 404 HTTP response. My workaround is checking the getPrevious() method of the exception:
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
if ($e->getPrevious() instanceof ModelNotFoundException) {
return response()->json([
'status' => 204,
'message' => 'Data not found'
], 200);
}
return response()->json([
'status' => 404,
'message' => 'Target not found'
], 404);
}
});
And then we will know that this exception come from ModelNotFoundException and return a different response with NotFoundHttpException.
Edit
This is why ModelNotFoundException thrown as NotFoundHttpException
This one is my Handler file:
use Throwable;
public function render($request, Throwable $exception)
{
if( $request->is('api/*')){
if ($exception instanceof ModelNotFoundException) {
$model = strtolower(class_basename($exception->getModel()));
return response()->json([
'error' => 'Model not found'
], 404);
}
if ($exception instanceof NotFoundHttpException) {
return response()->json([
'error' => 'Resource not found'
], 404);
}
}
}
This one is only for all request in API route. If you want to catch all request, so remove the first if.
Please note that by default Laravel emits a JSON representation of an exception ONLY when you send a request with the header parameter Accept: application/json! For all other requests, Laravel sends normal HTML rendered output.

Laravel 5.7 ModelNotFoundException not return json for API calls

I want to return a json response when an api call is made to a laravel 5.7 app api route when the model is not found. To do this I have modified the render() method of app\Exceptions\Handler.php like this
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && $request->wantsJson()) {
return response()->json(['message' => 'Not Found!'], 404);
}
return parent::render($request, $exception);
}
and my controller show() method is using a Book model like this
public function show(Book $book)
{
return new BookResource($book->load('ratings'));
}
Test on postman, a get call to localhost:8000/api/books/1 (id 1 has been deleted) keeps returning the default laravel 404 not found page instead of json.
Have I missed a step or something? I also noticed that adding a conditional statement inside the controller show() method like this
public function show(Book $book)
{
if ($book) {
return new BookResource($book->load('ratings'));
} else {
return response()->json(['message' => 'Not found'], 404);
}
}
returns the same html result instead of json.
What will be the proper way to handle this scenario?
Your code is correct. The problem is that you are probably testing it on a Local environment so in your .env you have set:
APP_DEBUG=true, switch it to APP_DEBUG=false and you will see your custom message.
PS: $request->wantsJson() is not necessary if your clients send the correct header info, eg: 'accept:application/json'
You can remove $request->wantsJson
or you can set the header in your request "Accept" => "application/json"
May this can help you:
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && ($request->wantsJson() || $request->ajax())) {
return response()->json(['message' => 'Not Found!'], 404);
}
return parent::render($request, $exception);
}

Laravel Controller-Model Exception Handling structure with database transactions

With regards to architecture, which of the two is a good practice when throwing exceptions from model to controller?
Structure A:
UserController.php
public function updateUserInfo(UserInfoRequest $request, UserModel $userModel)
{
$isError = false;
$message = 'Success';
try {
$message = $userModel->updateUserInfo($request->only(['username', 'password']));
} catch (SomeCustomException $e) {
$isError = true;
$message = $e->getMessage();
}
return json_encode([
'isError' => $isError,
'message' => $message
]);
}
UserModel.php
public function updateUserInfo($request)
{
$isError = false;
$message = 'Success';
$username = $request['username'];
$password = $request['password'];
try {
$this->connect()->beginTransaction();
$this->connect()->table('users')->where('username', $username)->update(['password' => $password]);
$this->connect()->commit();
} catch (\Exception $e) {
$this->connect()->rollback();
$isError = true;
$message = $e->getMessage();
}
return [
'isError' => $isError,
'message' => $message
];
}
Structure B:
UserController.php
public function updateUserInfo(UserInfoRequest $request, UserModel $userModel)
{
$isError = false;
$message = 'Success';
try {
$userModel->updateUserInfo($request->only(['username', 'password']));
} catch (SomeCustomException $e) {
$isError = true;
$message = $e->getMessage();
} catch (QueryException $e) {
$isError = true;
$message = $e->getMessage();
}
return json_encode([
'isError' => $isError,
'message' => $message
]);
}
UserModel.php
public function updateUserInfo($request)
{
$username = $request['username'];
$password = $request['password'];
try {
$this->connect()->beginTransaction();
$this->connect()->table('users')->where('username', $username)->update(['password' => $password]);
$this->connect()->commit();
} catch (\Exception $e) {
$this->connect()->rollback();
throw new QueryException();
}
}
In Structure A, the model catches any exception, rollback the transaction and return if it has an error or none to the controller. The controller then just return whatever is returned from the model.
While in Structure B the model catches any exception, rollback the transaction then throw a QueryException if an exception occurred. The controller then catches the thrown QueryException from the model then the return if it has an error or none.
The reason why Structure B still have a catch is that the model should be the one to do the rollback. If I were to remove the try-catch on the model here and the controller to directly catch an exception, then the rollback will be handled on the controller which I think kind of clutters the functionality of the controller.
Let me know your thoughts.
Thanks!
Why I think the approach from B is better:
Your Model should only include the logical part: This includes the communication with the database (transaction and rollback), not the formatting for the error message you want to print to the user.
Keep your model clean: It's the most important part of the MVC-structure. If you mess it up it will be very difficult to find any errors.
Outsourcing the error-handling: if you put it in the controller you have the choice to handle it there (maybe you want some special formatted output for this method or you need some other functions to call) or you handle it in the App\Exceptions\Handler. In this case you can render this error message here and don't have to do it in the controller.
So if you don't need any special function calls and want to use the full power of Laravel I would suggest you Structure C
UserController.php
public function updateUserInfo(UserInfoRequest $request, UserModel $userModel)
{
$userModel->updateUserInfo($request->only(['username', 'password']));
return response()->json(['message' => 'updated user.']);
}
UserModel.php
public function updateUserInfo($request)
{
$username = $request['username'];
$password = $request['password'];
try {
$this->connect()->beginTransaction();
$this->connect()->table('users')->where('username', $username)->update(['password' => $password]);
$this->connect()->commit();
} catch (\Exception $e) {
$this->connect()->rollback();
throw new QueryException();
}
}
App\Exceptions\Handler
public function render($request, Exception $exception)
{
//catch everything what you want
if ($exception instanceof CustomException) {
return response()->json([
'message' => $exception->getMessage()
], 422);
}
return parent::render($request, $exception);
}
You have a clean separation of the Database stuff (Model), the presentation stuff (Controller) and the error handling (Handler). Structure C allows you to reuse the error-handling in other functions where you have the same situation in another controller function.
This is my opinion but I am open to discuss about any scenario where you think this approach isn't the best solution.
First of all, for your example, you don't even need to use Transaction. You are performing just one query. so why do you need to rollback? Which query you want to rollback? A transaction should be used when you need a set of changes to be processed completely to consider the operation complete and valid. If the first one is successful, but any of the following has any error, you can rollback everything as if nothing was ever done.
Secondly, Lets come to the point good practice or best practice. Laravel suggest Thin controller and Thick model. So all of your business logic should be in model or even better in a repository. Controller will be act as a broker. It will collect data from repository or model and pass it to view.
Alternately, laravel provides some nice and convenient way to organize your codes. You can use Event and Observers for concurrent operation in your model.
Best practice is varies based on the knowledge and experience of the users. So who knows, the best answer for your question is yet to come.
I'd rather keep the controllers and any other part of the system that interacts with the models, as agnostic as possible about the inner workings of the model. So for instance I'd try to avoid being aware of QueryExceptions outside of the model and instead treat it as a plain PHP object whenever possible.
Also I'd avoid the custom JSON response structure and use HTTP statuses. If it makes sense, maybe the route for updating the user info returns the updated resource, or maybe a 200 OK is enough.
// UserModel.php
public function updateUserInfo($request)
{
$username = $request['username'];
$password = $request['password'];
try {
$this->connect()->beginTransaction();
$this->connect()->table('users')->where('username', $username)->update(['password' => $password]);
$this->connect()->commit();
return $this->connect()->table('users')->where('username', $username)->first();
// or just return true;
} catch (\Exception $e) {
$this->connect()->rollback();
return false;
}
}
// UserController.php
public function updateUserInfo(UserInfoRequest $request, UserModel $userModel)
{
$updated = $userModel->updateUserInfo($request->only(['username', 'password']));
if ($updated) {
return response($updated);
// HTTP 200 response. Returns JSON of updated user.
// Alternatively,
// return response('');
// (200 OK response, no content)
} else {
return response('optional message', 422);
// 422 or any other status code that makes more sense in the situation.
}
(Completely off-topic, I guess this is an example, but just in case, a reminder not to store plain text passwords.)
i don't understand, why you not watched Jeffry lesson, but for updating user you don't need try/catch section.
you controller method:
public function update(UpdateUserRequest $request, User $user) : JsonResponse
{
return response()->json($user->update($request->all()))
}
you request rules method:
public function rules(): array
{
return [
'username' => 'required|string',
'password' => 'required|min:6|confirmed',
];
}
And you Exception Handler render method:
public function render($request, Exception $exception)
{
if ($request->ajax() || $request->wantsJson()) {
$exception = $this->prepareException($exception);
if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
return $exception->getResponse();
} elseif ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return $this->unauthenticated($request, $exception);
} elseif ($exception instanceof \Illuminate\Validation\ValidationException) {
return $this->convertValidationExceptionToResponse($exception, $request);
}
// we prepare custom response for other situation such as modelnotfound
$response = [];
$response['error'] = $exception->getMessage();
if (config('app.debug')) {
$response['trace'] = $exception->getTrace();
$response['code'] = $exception->getCode();
}
// we look for assigned status code if there isn't we assign 500
$statusCode = method_exists($exception, 'getStatusCode')
? $exception->getStatusCode()
: 500;
return response()->json($response, $statusCode);
}
return parent::render($request, $exception);
}
Now, if you have Exception, Laravel give you in Json with status code != 200, else give success result!

How to catch authorization errors in Laravel's Handler render

I'm trying to show a custom error page, which I'd like to appear if the error wasn't a 'page not found' or a authentication issue (e.g. trying to access a page which the user doesn't have access to). I'm using the code below in Laravel 5.3's Handler.php. While the 404 part works, the authentication part doesn't (triggering this error just returns the 500 page instead). What am I missing?
public function render($request, Exception $e)
{
if ($e instanceof NotFoundHttpException || $e instanceof AuthorizationException || $e instanceof AuthenticationException) {
return parent::render($request, $e);
}
else {
return response()->view('errors.500', [
'sentryID' => $this->sentryID,
], 500);
}
}
Edit : Looks like you want to handle all the global error pages. Laravel uses symfony's exception handler to generate the error page text and style. This can be found at
vendor/symfony/debug/ExceptionHandler.php
It's used in vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php as
use Symfony\Component\Debug\ExceptionHandler as SymfonyExceptionHandler;
To handle every error and exception you can extend the method prepareResponse to app/Exceptions/Handler.php and make appropriate changes.
protected function prepareResponse($request, Exception $e)
{
if ($this->isHttpException($e)) {
return $this->toIlluminateResponse($this->renderHttpException($e), $e);
} else {
return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
}
}
You can check the underlying working of this method in vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php
End edit
You don't need to mess in the render method for this. Out of the box laravel searches for error views and renders them if available based on the error code. So for 404 and 500 you could just create the following two views and customize it in there.
resources/views/errors/404.blade.php
resources/views/errors/500.blade.php
This views get the exception, status and header information for you to display if needed. They are called like so
return response()->view("errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
For the authentication check. Laravel calls the unauthenticated method in app/Exceptions/Handler.php when a user is unauthenticated. This code by default redirects the users to login page or shows a json response. You can make you changes here.
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login');
}

How to send Laravel error responses as JSON

Im just move to laravel 5 and im receiving errors from laravel in HTML page. Something like this:
Sorry, the page you are looking for could not be found.
1/1
NotFoundHttpException in Application.php line 756:
Persona no existe
in Application.php line 756
at Application->abort('404', 'Person doesnt exists', array()) in helpers.php line
When i work with laravel 4 all works fine, the errors are in json format, that way i could parse the error message and show a message to the user. An example of json error:
{"error":{
"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"message":"Person doesnt exist",
"file":"C:\\xampp\\htdocs\\backend1\\bootstrap\\compiled.php",
"line":768}}
How can i achieve that in laravel 5.
Sorry for my bad english, thanks a lot.
I came here earlier searching for how to throw json exceptions anywhere in Laravel and the answer set me on the correct path. For anyone that finds this searching for a similar solution, here's how I implemented app-wide:
Add this code to the render method of app/Exceptions/Handler.php
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse($e->getMessage(), 422);
}
Add this to the method to handle objects:
if ($request->ajax() || $request->wantsJson()) {
$message = $e->getMessage();
if (is_object($message)) { $message = $message->toArray(); }
return new JsonResponse($message, 422);
}
And then use this generic bit of code anywhere you want:
throw new \Exception("Custom error message", 422);
And it will convert all errors thrown after an ajax request to Json exceptions ready to be used any which way you want :-)
Laravel 5.1
To keep my HTTP status code on unexpected exceptions, like 404, 500 403...
This is what I use (app/Exceptions/Handler.php):
public function render($request, Exception $e)
{
$error = $this->convertExceptionToResponse($e);
$response = [];
if($error->getStatusCode() == 500) {
$response['error'] = $e->getMessage();
if(Config::get('app.debug')) {
$response['trace'] = $e->getTraceAsString();
$response['code'] = $e->getCode();
}
}
return response()->json($response, $error->getStatusCode());
}
Laravel 5 offers an Exception Handler in app/Exceptions/Handler.php. The render method can be used to render specific exceptions differently, i.e.
public function render($request, Exception $e)
{
if ($e instanceof API\APIError)
return \Response::json(['code' => '...', 'msg' => '...']);
return parent::render($request, $e);
}
Personally, I use App\Exceptions\API\APIError as a general exception to throw when I want to return an API error. Instead, you could just check if the request is AJAX (if ($request->ajax())) but I think explicitly setting an API exception seems cleaner because you can extend the APIError class and add whatever functions you need.
Edit: Laravel 5.6 handles it very well without any change need, just be sure you are sending Accept header as application/json.
If you want to keep status code (it will be useful for front-end side to understand error type) I suggest to use this in your app/Exceptions/Handler.php:
public function render($request, Exception $exception)
{
if ($request->ajax() || $request->wantsJson()) {
// this part is from render function in Illuminate\Foundation\Exceptions\Handler.php
// works well for json
$exception = $this->prepareException($exception);
if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
return $exception->getResponse();
} elseif ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return $this->unauthenticated($request, $exception);
} elseif ($exception instanceof \Illuminate\Validation\ValidationException) {
return $this->convertValidationExceptionToResponse($exception, $request);
}
// we prepare custom response for other situation such as modelnotfound
$response = [];
$response['error'] = $exception->getMessage();
if(config('app.debug')) {
$response['trace'] = $exception->getTrace();
$response['code'] = $exception->getCode();
}
// we look for assigned status code if there isn't we assign 500
$statusCode = method_exists($exception, 'getStatusCode')
? $exception->getStatusCode()
: 500;
return response()->json($response, $statusCode);
}
return parent::render($request, $exception);
}
On Laravel 5.5, you can use prepareJsonResponse method in app/Exceptions/Handler.php that will force response as JSON.
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return $this->prepareJsonResponse($request, $exception);
}
Instead of
if ($request->ajax() || $request->wantsJson()) {...}
use
if ($request->expectsJson()) {...}
vendor\laravel\framework\src\Illuminate\Http\Concerns\InteractsWithContentTypes.php:42
public function expectsJson()
{
return ($this->ajax() && ! $this->pjax()) || $this->wantsJson();
}
I updated my app/Exceptions/Handler.php to catch HTTP Exceptions that were not validation errors:
public function render($request, Exception $exception)
{
// converts errors to JSON when required and when not a validation error
if ($request->expectsJson() && method_exists($exception, 'getStatusCode')) {
$message = $exception->getMessage();
if (is_object($message)) {
$message = $message->toArray();
}
return response()->json([
'errors' => array_wrap($message)
], $exception->getStatusCode());
}
return parent::render($request, $exception);
}
By checking for the method getStatusCode(), you can tell if the exception can successfully be coerced to JSON.
If you want to get Exception errors in json format then
open the Handler class at App\Exceptions\Handler and customize it.
Here's an example for Unauthorized requests and Not found responses
public function render($request, Exception $exception)
{
if ($exception instanceof AuthorizationException) {
return response()->json(['error' => $exception->getMessage()], 403);
}
if ($exception instanceof ModelNotFoundException) {
return response()->json(['error' => $exception->getMessage()], 404);
}
return parent::render($request, $exception);
}

Categories