Laravel findorfail()重定向 [英] Laravel findorfail() redirect

查看:293
本文介绍了Laravel findorfail()重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

如果我们在数据库表中有一个ID,则它将带有findorfail()

if we have an id in the DB table then that will come up with findorfail(),

但是,如果我们向网址中添加不存在的ID,如下所示:

but if we add not existing id to the url like this :

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

然后没有找到找到的查询页面.

Then no query found larvel page comes up.

如果没有ID,如何重定向到某些路由.

How can I redirect to some route if we have no id.

推荐答案

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

Add this to your uses in your controller

use Illuminate\Database\Eloquent\ModelNotFoundException;//find or fail error exception class.

并为此修改当前代码

 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
    }
}

这篇关于Laravel findorfail()重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆