Skip to content
Advertisement

Laravel findorfail() redirect

I have the following code :

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

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

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

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

Then no query can be found and laravel page comes up.

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

Advertisement

Answer

Add this to your uses in your controller

use IlluminateDatabaseEloquentModelNotFoundException;//find or fail error exception class.

and modify you current code to this

 public function showTestProfile($id){
    try{
        $auth = Auth::user();
        $tests = AppTest::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
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement