繁体   English   中英

在 findOrFail 上重定向到 404 页面之前调用函数

[英]calling a function before redirecting to 404 page on findOrFail

当我从数据库中删除某些内容时……比如说一个博客,我可能想将该博客的链接重定向到另一个链接而不是 404 页面

我有一个名为setting_redirects的表:

setting_redirects : id , deleted_link , redirect_link 

我将在此表中存储已删除的链接和新链接

这就是我展示博客的方式

function show( $blog_id ){

   $blog = Blog::findOrFail($blog_id);
}

问题是如果没有找到findOrFail将自动将用户重定向到 404 页面...我希望能够检查setting_redirects以查看该博客是否有重定向.... 如果是,则重定向到该新链接,否则转到404

像这样的东西

function show( $blog_id ){

   $blog = Blog::find($blog_id);
   if(!$blog)
   {
      $redirect_available = SettingRedirect::where('deleted_link ' ,  Request::url() ) ->first();
     if($redirect_available )
       return redirect( $redirect_available-> redirect_link );
      else 
       abort(404);
   }
}

但我希望我的所有表格都使用这个,不仅是博客,而且我不想在我所有的控制器中编写这段代码

有没有办法在不改变我所有控制器的情况下做到这一点? 在进入 404 页面之前可能是一个中间件?

findOrFail抛出一个ModelNotFoundException 我认为你可以简单地抓住并重新抛出它。

try {
    $blog = Blog::findOrFail($blog_id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    $redirect_available = SettingRedirect::where('deleted_link', Request::url())->first();
    if ($redirect_available)
        return redirect($redirect_available->redirect_link);

    throw $e;
}

或者,您可以将此逻辑放在register()方法内的app/Exceptions/Handler.php文件中。

<?php

namespace App\Exceptions;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    public function register()
    {
        $this->renderable(function (NotFoundHttpException $e, $request) {
            // this is to make sure the exception was caused by a findOrFail operation 
            if ($e->getPrevious() instanceof ModelNotFoundException) {
                $redirect_available = SettingRedirect::where('deleted_link', $request->url())->first();

                if ($redirect_available) {
                    return redirect($redirect_available->redirect_link);
                }
            }
        });
    }
}

第一行的原因是
$this->renderable(function (NotFoundHttpException $e, $request) { ... })而不是
$this->renderable(function (ModelNotFoundException $e, $request) { ... })

是因为 Laravel 在ModelNotFoundException可用于异常处理程序之前将其转换为NotFoundHttpException

我认为需要在删除操作时更改该特定记录的状态,代码为 404,如果查询可执行则包含“mypage.php”; 否则会显示默认的 404 页面

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM