How to access array elements in foreach loop in Laravel
P粉312195700
P粉312195700 2023-09-11 00:04:14
0
1
595

I created a custom array to store the questions and answers, but whenever I try to access these array elements it gives me Trying to read the property "questions" on the array (

Actually, I have created a custom array. When I try to create without custom array it works fine. Like getting data from direct eloquent model works fine

This is my JSON response...

@foreach ($questionsArray as $i => $data)
                              <div class=" p-3 m-1 text-left">
                                <p class="font-weight-bold">Q.{{$i + 1}} {{$data->question}}</p>
                              // error is here !
                              
                              @endforeach
$questionsArray = array();

        foreach ($questions as $question) {

            $answers = tbl_answer::where('answer_question_table_id', $question->question_id)->get();
            $questionsArray[] = array(
                "question" => array($question),
                "answers"  => array($answers)
            );
        }

P粉312195700
P粉312195700

reply all(1)
P粉004287665

Associative arrays and objects are not the same thing in php.

Here you are pushing an array with keys question and answers into a questionsArray:

$questionsArray[] = array(
                "question" => array($question),
                "answers"  => array($answers)
            );

So you should use array access to read it. Assuming $data is an element of $questionsArray, you will have {{ $data['question'] }} instead of { { $data ->Question}}

Of course, you've wrapped some question entities or associative arrays in another array and put it into $data['question]`, so the printout won't work.

Maybe try something like this:

$questionsArray[] = [
                "question" => $question,
                "answers"  => $answers
            ];

Then read the properties of the problem in the blade file:

@foreach ($questionsArray as $i => $data)

    <div class=" p-3 m-1 text-left">
    <p class="font-weight-bold">Q.{{$i + 1}} {{$data['question']['question_title']}}</p>
                              
@endforeach
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template