Search code examples
phpexceptionlaravelcustom-exceptions

Get model of Laravel exceptions


I'm trying to make custom exceptions messages with Laravel 4.2. I use a function firstorfail() in a route to load a profile page, and I've made an error handler, following the doc (link)

App::error(function(ModelNotFoundException $e)
{       
    return View::make('erreur404')->with('error', 'This user doesn\'t exist'); ;
});

But I would like to add custom messages (like "This user doesn't exist") for the different pages, and not the same every time this error occurs.

I've tried to access to $e->model, but it's a protected element so I can't have any information from the exception.

I can't use the default exception message because my website is in French.


Solution

  • Use the getModel method:

    App::error(function(ModelNotFoundException $e)
    {
        $model = $e->getModel();
    
        $namespacedClassName = get_class($model);
    
        $className = last(explode('\\', $namespacedClassName));
    
        // Now do with it what you will...
    });