Laravel findorfail() 重定向

Gam*_*mer 2 php laravel

我有以下代码:

    public function showTestProfile($id){
        $auth = Auth::user();
        $tests = App\Test::findorfail($id);
        return view('profile',compact('auth','tests','members'));
    }
Run Code Online (Sandbox Code Playgroud)

如果我们在 DB 表中有一个 id,那么就会出现findorfail()

但是如果我们像这样将不存在的 id 添加到 url 中:

http://NewPro.dev/user-profile/24645645456

然后没有查询发现 larvel 页面出现。

如果我们没有 id,我如何重定向到某个路由。

the*_*edA 6

将此添加到您在控制器中的用途中

use Illuminate\Database\Eloquent\ModelNotFoundException;//find or fail error exception class.
Run Code Online (Sandbox Code Playgroud)

并将您当前的代码修改为此

 public function showTestProfile($id){
    try{
        $auth = Auth::user();
        $tests = App\Test::findorfail($id);
        return view('profile',compact('auth','tests','members'));
    }
    catch(ModelNotFoundException $err){
        //if id doesnt exist it will skip return view('profil..
        //and excute whatever in this section
    }
}
Run Code Online (Sandbox Code Playgroud)