【问题标题】:Handle module not found in laravel 7 routing在 laravel 7 路由中找不到句柄模块
【发布时间】:2021-10-14 06:53:15
【问题描述】:

假设我有一些

Route::get('/path/{model}', 'Controller@method');

mysite.com/path/1 没有模型#1 的情况下,我得到 404,这是 Laravel 的默认行为 我想为特定路由组/特定路由

处理(基本上,重定向到另一个命名路由)“NoModelFound”

由于该路由存在,Route::fallbackRoute::any 不会在此处触发。

我知道 Laravel 8 中有一个 Route()->missing 方法,但我有 Laravel 7 并且无法更新。 另外,我以最好的方式搜索路线内的解决方案(web.php

有什么解决办法吗?提前谢谢

【问题讨论】:

    标签: laravel laravel-7 laravel-routing


    【解决方案1】:

    您可以在App\Exceptions\Handler 类中全局处理异常。如果你真的和我的意思是真的想具体处理 ModelNotFoundException 仅针对某些路线,那么你可以做一些类似的事情

      // Exception Handle class
      public function render($request, Exception $exception)
        {
           
            if(
                $request->is('*path/') &&  // or string match
                $exception instanceof ModelNotFoundException
            ){
                redirect()->to('where-ever');
            }
        }
    
    

    如果您只想在ModelNotFoundException 发生时重定向用户,那么您可以这样做,

      // Exception Handle class
      public function render($request, Exception $exception)
        {
           
            if(
                
                $exception instanceof ModelNotFoundException
            ){
                redirect()->to('where-ever');
            }
        }
        
    

    另一种方法是使用中间件并检查某个模型,如果它不存在,则重定向用户。取决于你想要做什么。你可以在这里找到更多信息

    https://laravel.com/docs/8.x/middleware https://laravel.com/docs/8.x/errors#the-exception-handler

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2023-03-19
      • 2015-05-23
      • 2020-03-26
      相关资源
      最近更新 更多