cookie
cookie

Reputation: 2728

Using ModelNotFoundException

I'm starting out in Laravel and want to discover more about using error handling especially the ModelNotFoundException object.

<?php
 class MenuController extends BaseController {

    function f() {
          try {
                $menus = Menu::where('parent_id', '>', 100)->firstOrFail();
            } catch (ModelNotFoundException $e) {
                $message = 'Invalid parent_id.';
                return Redirect::to('error')->with('message', $message);
            }
        return $menus;
    }
  }
?>

In my model:

<?php
 use Illuminate\Database\Eloquent\ModelNotFoundException;  

 class Menu extends Eloquent {
    protected $table = 'categories'; 
}

?>

Of course for my example there are no records in 'categories' that have a parent_id > 100 this is my unit test. So I'm expecting to do something with ModelNotFoundException.

If I run http://example.co.uk/f in my browser I receive:

Illuminate \ Database \ Eloquent \ ModelNotFoundException
No query results for model [Menu].

the laravel error page - which is expected, but how do I redirect to my route 'error' with the pre-defined message? i.e.

<?php
// error.blade.php

{{ $message }}
?>

If you could give me an example.

Upvotes: 18

Views: 40086

Answers (4)

Mehmet B&#252;t&#252;n
Mehmet B&#252;t&#252;n

Reputation: 749

When you use the render() function in Laravel 8.x and higher versions, you will encounter 500 Internal Server Error. This is because with Laravel 8.x errors are checked within the register() function (Please check this link)

I'm leaving a working example here:

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    public function register()
    {

        $this->renderable(function (ModelNotFoundException $e, $request) {
            return response()->json(['status' => 'failed', 'message' => 'Model not found'], 404);
        });
        $this->renderable(function (NotFoundHttpException $e, $request) {
            return response()->json(['status' => 'failed', 'message' => 'Data not found'], 404);
        });
    }
}

Upvotes: 4

Mahedi Hasan
Mahedi Hasan

Reputation: 1078

Try this

  try {

      $user = User::findOrFail($request->input('user_id'));

    } catch (ModelNotFoundException $exception) {

       return back()->withError($exception->getMessage())->withInput();
    }

And to show error, use this code in your blade file.

 @if (session('error'))
   <div class="alert alert-danger">{{ session('error') }}</div>
 @endif

And of course use this top of your controller

use Illuminate\Database\Eloquent\ModelNotFoundException;  

Upvotes: 1

Razor
Razor

Reputation: 9835

Just use namespace

try {
    $menus = Menu::where('parent_id', '>', 100)->firstOrFail();
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    $message = 'Invalid parent_id.';
    return Redirect::to('error')->with('message', $message);
}

Or refer it to an external name with an alias

use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;

Upvotes: 12

The Alpha
The Alpha

Reputation: 146191

In Laravel by default there is an error handler declared in app/start/global.php which looks something like this:

App::error(function(Exception $exception, $code) {
    Log::error($exception);
});

This handler basically catches every error if there are no other specific handler were declared. To declare a specific (only for one type of error) you may use something like following in your global.php file:

App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $exception) {

    // Log the error
    Log::error($exception);

    // Redirect to error route with any message
    return Redirect::to('error')->with('message', $exception->getMessage());
});

it's better to declare an error handler globally so you don't have to deal with it in every model/controller. To declare any specific error handler, remember to declare it after (bottom of it) the default error handler because error handlers propagates from most to specific to generic.

Read more about Errors & Logging.

Upvotes: 15

Related Questions