Laravel中的404 问题

相信404对于开发者都不会陌生,404代表的请求的资源在服务端不存在,也就是Not Found.

如果在Laravel 项目中出现了404的问题,一般是以下两种情况:

1. 请求的路由地址根本不存在。

2. 请求的路由地址是存在的,但是依然是404,那么可以断定是路由控制器中的逻辑出现了模型实例查找不到的问题,一般是在调用模型方法firstOrFail或者findOrFail的时候:

Route::get('/api/flights/{id}', function ($id) {
    return App\Models\Flight::findOrFail($id);
});

如果请求**/api/flights/2**这个路由返回了404,那么应该是id=2的模型记录在DB中没有找到。

在Laravel的官方文档对于这种情况是这么说的:

Not Found Exceptions

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

$model = App\Models\Flight::findOrFail(1);

$model = App\Models\Flight::where('legs', '>', 100)->firstOrFail();

If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:

Route::get('/api/flights/{id}', function ($id) {
    return App\Models\Flight::findOrFail($id);
});
                                                                                                  

简单的说就是模型实例未找到,内部会抛出Illuminate\Database\Eloquent\ModelNotFoundException异常,如果未对它做捕获,框架会直接抛出404的错误信息。