It seems like you're trying to determine the correct URL for an image based on whether it's stored locally or via a public disk. Your ternary operator approach is correct in concept, but it needs a slight adjustment to properly check the existence of the file in the storage.
Here's a cleaner way to handle this using a ternary operator directly within the Blade template. This approach checks if the image exists in the public disk, and if not, it falls back to using the asset() helper. This is assuming that images not in the public disk are accessible directly via the public/ directory.
<img src="{{ Storage::disk('public')->exists($post->image) ? Storage::url($post->image) : asset($post->image) }}" alt="Post Image">
This single line replaces the @if directive block and is more concise. Here’s what it does:
-
Storage::disk('public')->exists($post->image): This checks if the image exists in the public disk. -
Storage::url($post->image): If the image exists, this method generates a URL for it. -
asset($post->image): If the image does not exist in the public storage, theasset()helper generates a URL assuming the image is in the public directory.
Make sure that the paths stored in $post->image are relative to the storage disk's root for Storage::url() and to the public directory for asset(). This solution assumes that your images are either stored in the storage/app/public directory (and thus accessible via the public/storage symlink) or directly in the public directory.