Laravel 5.6 当模型处于参数的类型提示中时未找到页面
Laravel 5.6 not found page when model is in type hint for parameter
我有一个显示图像的方法,当在文件系统上找不到图像时,它应该 return 一个未找到的图像。
在我在方法中指定参数类型之前,所有这些都工作正常。
当我的代码是这样的时候,它不起作用:
public function showImage( LibraryFile $image, string $name ): BinaryFileResponse {
if ( ( $image->thumbnails[ $name ] ?? null ) && File::exists( $image->thumbnails[ $name ] ) ) {
return response()
->file( $image->thumbnails[ $name ] );
}
return response()
->file( public_path( 'images/no-image-available.png' ) );
}
它确实是这样工作的:
public function showImage( $image, string $name ): BinaryFileResponse {
if ( ( $image->thumbnails[ $name ] ?? null ) && File::exists( $image->thumbnails[ $name ] ) ) {
return response()
->file( $image->thumbnails[ $name ] );
}
return response()
->file( public_path( 'images/no-image-available.png' ) );
}
我想这可能是因为找不到模型,因此 Laravel 决定抛出一个 404。有什么办法可以改变这个吗?
您应该像这样在 Route model binding 中使用自定义分辨率绑定:
Route::bind('image', function ($value) {
return App\LibraryFile::find($image) ?? abort(response()
->file( public_path( 'images/no-image-available.png' )));
});
到 return 自定义响应以防找不到模型
我有一个显示图像的方法,当在文件系统上找不到图像时,它应该 return 一个未找到的图像。 在我在方法中指定参数类型之前,所有这些都工作正常。
当我的代码是这样的时候,它不起作用:
public function showImage( LibraryFile $image, string $name ): BinaryFileResponse {
if ( ( $image->thumbnails[ $name ] ?? null ) && File::exists( $image->thumbnails[ $name ] ) ) {
return response()
->file( $image->thumbnails[ $name ] );
}
return response()
->file( public_path( 'images/no-image-available.png' ) );
}
它确实是这样工作的:
public function showImage( $image, string $name ): BinaryFileResponse {
if ( ( $image->thumbnails[ $name ] ?? null ) && File::exists( $image->thumbnails[ $name ] ) ) {
return response()
->file( $image->thumbnails[ $name ] );
}
return response()
->file( public_path( 'images/no-image-available.png' ) );
}
我想这可能是因为找不到模型,因此 Laravel 决定抛出一个 404。有什么办法可以改变这个吗?
您应该像这样在 Route model binding 中使用自定义分辨率绑定:
Route::bind('image', function ($value) {
return App\LibraryFile::find($image) ?? abort(response()
->file( public_path( 'images/no-image-available.png' )));
});
到 return 自定义响应以防找不到模型