phplaravellaravel-bladeternary

Ternary operator. && does not work. Laravel, Blade


I have an image Storage that stores images from users' personal pages. The name of the image is also stored in the img field of the users table in the database. I want to show it if there is a name in DB and an image in storage, otherwise I want to show a default image. I tried this but && doesn't work. I guess I'm doing something wrong:

<img src="{{ ((Auth::user()->img) && (Storage::url('users/'.Auth::user()->img))) ? (Storage::url('users/'.Auth::user()->img)) : '/img/svg/laptop-house-solid.svg' }}">

Solution

  • The reason was in different types of data. In the database I had a string, and in Storage there was an object (if I call it correctly) i.e. image, so the check didn't work. You can use the Storage::exists() facade function to check if an image exists.

    <img src="{{ ((Auth::user()->img) && (Storage::disk('public')->exists('users/'.Auth::user()->img))) ? (Storage::url('users/'.Auth::user()->img)) : '/img/svg/laptop-house-solid.svg' }}">