Trying to get property 'path' of non-object

Viewed 418

Hello I am having the above error in production but all works well in development. I am using the code bellow to get the path to the main image for the property but it defaults into the else despite the if not being false plus the else does not find the paths even when dump shows that the object has been returned //check if there are hotels in the selected destination

    if($hotels->isNotEmpty()){

        //Loop through the hotels

        foreach($hotels as $hotel){

            //get hotels main image

            $banner = Photo::where(['p_id'=>$hotel->id])->where(['is_main'=>1])->first();

            $altbanner = Photo::where(['p_id'=>$hotel->id])->first();

            $banner_path = "";

            $altText = "";

            if($banner!=null){

                $banner_path = $banner->path;

                $altText = $banner->alt_text;

            }else{

                $banner_path = $altbanner->path;

                $altText = $altbanner->alt_text;

            }
2 Answers

Have you checked your database if each hotel has an image? Based on your question and explanation, there is a part of the for each that returns null for the image hence the if part fails and the else return the error. If that is the case then you may want to check and sort it by uploading the image or modifying your checks to handle cases where no image is found.

I think the way you are using the where clause isn't right

foreach($hotels as $hotel){

  //get hotels main image

  $banner = Photo::where('p_id',$hotel->id)->where('is_main',1)->first();

  $altbanner = Photo::where('p_id',$hotel->id)->first();

  // .....

  if($banner){

     $banner_path = $banner->path;
    // ......
Related