Ad

Invalid Argument Supplied For Foreach() When Trying To Navigate Through Object. Blade - Laravel

- 1 answer

I'm making a pdf report to download, this is the relevant data. I'm trying to navigate through but I'm having trouble

[ 
   { 
      "id":1,
      "name":"asdfasd",
      "description":"fasdfasdfafa",
      "user_id":1,
      "anonymous":0,
      "created_at":"2019-12-09 10:30:50",
      "updated_at":"2019-12-09 10:33:25",
      "survey_questions":[ 
         { 
            "id":1,
            "question":"asfdasdfsdf",
            "user_id":1,
            "survey_section_id":1,
            "response_type_id":1,
            "optional":0,
            "num":null,
            "rank":null,
            "show_text":0,
            "created_at":"2019-12-09 10:29:27",
            "updated_at":"2019-12-09 10:29:27",
            "pivot":{ 
               "survey_id":1,
               "survey_question_id":1
            }
         }
      ],
      "answer":[ 

      ],
      "evaluation":{ 
         "id":1,
         "survey_id":1,
         "init_date":"2019-12-04 00:00:00",
         "end_date":"2019-12-07 00:00:00",
         "report_date":"2019-12-08 00:00:00",
         "created_at":"2019-12-09 10:30:50",
         "updated_at":"2019-12-09 10:33:25",
         "evaluation_results":[ 

         ]
      }
   }
]

It's called $survey, I've tried doing a couple things

$survey->name; //works
$survey->survey_questions; //no result when there should be
$survey->evaluation; //works while the survey_questions doesn't

I would like to access the other stuff like survey_questions, answer and in turn access the stuff inside there.

When I try this I get the mentioned error Invalid argument supplied for foreach()

@foreach($survey->survey_questions as $question)
   {{$question}}
@endforeach

This is how I'm sending the data from the controller

$survey = Survey::with('surveyQuestions', 'answer', 
'evaluation', 'evaluation.evaluationResults')
            ->where('id', $id)->first();

$pdf = App::make('dompdf.wrapper');
$pdf->loadView('pdf.report', ['survey' => $survey]);
return $pdf->stream();

What is the correct way to be able to access this data?

Ad

Answer

I believe you have surveyQuestions() method define in Survey Model, If so then your foreach should be like

@foreach($survey->surveyQuestions as $question)
   {{$question}}
@endforeach
Ad
source: stackoverflow.com
Ad