假设在我们的Controller中:
$some_id = 6;
$contacts = Contact::findOrFail($some_id);
如果findOrFail()找不到id为6的contact,那么页面就会跳转到404错误:
那么我们可以在resouces/view/errors/文件夹下,新建一个叫404.blade.php的文件,里面放上我们想要输出的错误信息,比如:
<!DOCTYPE html>
<html lang="cn">
<head>
<title>Oops!</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<p class="display-4 text-danger text-center mt-5">Oops! The page you are looking for cannot be found.</p>
</div>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
然后刷新刚才的route,我们会看到错误已经变成了我们自定义的错误了:
这样是不是就很User Friendly了呢!

本文介绍如何在Laravel框架中使用Contact模型的findOrFail方法处理不存在的数据,并自定义404错误页面。
1180

被折叠的 条评论
为什么被折叠?



