Search code examples
laravelmodelreturnassetsfile-exists

If more than 1 image file exists in Laravel Model


I found out that im unable to use assets in file_exists if i put them in the controller, thats why im using them inside the model. Anyway in my code i need to output 3 different pictures if each of them are available.

This is my current code

if(File::exists( public_path().'/image/hospitals/' .$this->HospitalID . '.jpg')){
            return asset('/image/hospitals/' .$this->HospitalID . '.jpg');
        }  else {
            return asset('/image/hospitals/default.jpg');
        }

For now this code is only able to output 1 image and default it if the image is not available. My question is, how do I input 3 images? My file names for the 3 images are:

[HospitalID]_1.jpg [HospitalID_2].jpg [HospitalID_3].jpg

for example 10_1.jpg 10_2.jpg 10_3.jpg

thanks a ton!


Solution

  • I assume that in your object, that might be Hostpital, you store those file names or ids, so you could just return an array of IDs or even simpler, return the hospital object, then in your controller you should do something like:

    class HospitalController extends Controller {
        // some code
        public function method_name($id) {
            $hospital = Hospital::find($id);
            // some other stuff
            return view('name_of_view')->withHospital($hospital);
    }
    

    Then in your view you could do:

            @foreach ($hospital->images as $image_id)
            <img src={{ public_path() . '/image/hospitals/' . $image_id ".jpg" }} />
            @endforeach