Laravel自定义ModelNotFoundException处理每个路由组

I have two route groups in my Laravel application, one for an API and one for the website itself. I've added the following code in global.php for error handling of my API.

App::error(function(ModelNotFoundException $e)
{
   return Response::json('', 404);
});

But not this obviously also has effect on my normal website, where I want to return a normal view when the ModelNotFoundException occurs. Like so:

App::error(function(ModelNotFoundException $e)
{
   return Response::view('404.html', [], 404);
});

How can I setup different error handlers for different route groups?

I think you shouldn't care what part of the site that threw the error, but instead respond with whatever format the client requested. In general this is set in the Accepts header of the request and can be accessed in Laravel by:

if (Request::format() == 'json')
{
    //
}

(above is taken from the documentation)

In your case, this would turn your error handling function to this:

App::error(function(ModelNotFoundException $e)
{
   if (Request::format() == 'json') {
       return Response::json('', 404);
   } else {
       return Response::view('404.html', [], 404);
   }
});

This automatically covers you if, for instance, you add an non-API AJAX request to the main portion of your website (for whatever reason) that could potentially trigger a ModelNotFoundException. As long as your client sends the appropriate request headers, you're good.

You could try with changing environment. For selected group you could change environment using:

$app->setEnvironment('enviromentname');

and create new environmentname.php file in start directory

But I don't know if it will work.

You could also create a session variable and in App:error add code depending on this session variable:

   $value = Session::get('type');

  if ($value == 'onetype') {
     // something
  }
  else {
    // something else
  }