Ad

Laravel 5.6 Not Found Page When Model Is In Type Hint For Parameter

I have a method to show images, when the image is not found on the filesystem, it should return a not found image. All of this is working fine until I specify the type of the parameter in the method.

It doesn't work when my code is like this:

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' ) );
}

It does work like this:

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' ) );
}

I think this is probably because the model cannot be found and therefore Laravel decides to throw a 404. Is there any way to change this?

Ad

Answer

You should use custom resolution binding in Route model binding like this:

Route::bind('image', function ($value) {
    return App\LibraryFile::find($image) ?? abort(response()
    ->file( public_path( 'images/no-image-available.png' )));
});

to return custom response in case model is not found

Ad
source: stackoverflow.com
Ad