I have the following code :
JavaScript
x
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
JavaScript
use IlluminateDatabaseEloquentModelNotFoundException;//find or fail error exception class.
and modify you current code to this
JavaScript
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
}
}