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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With