Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ModelNotFoundException

Tags:

laravel

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.

like image 408
cookie Avatar asked May 29 '14 16:05

cookie


1 Answers

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.

like image 117
The Alpha Avatar answered Sep 19 '22 14:09

The Alpha