Ruka Xing
Ruka Xing

Reputation: 642

Laravel nested foreach by 2 different Models

I tried this. problem is, How to foreach data from different Models?

Trying to get property of non-object (View: C:\wamp64\www\zainsurgalt\resources\views\choices\index.blade.php)

Controller

$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get();
$choices = Choice::where('user_id',Auth::id())->pluck('question_number')->toArray();
return view('choices.index',compact('duplicates','choices'));

View

@foreach ($duplicates as $duplicate)
        <tr>
            <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
            <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
            <td style="text-align: center;">{{ $duplicate->total }}</td>
            <td style="text-align: center;">
                @foreach ($choices as $choice)
                    {{ $choice->question_number }}
                @endforeach
            </td>
            <td>
            <a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td>
        </tr>
    @endforeach

result of dd($choices) before foreach

array:34 [▼
0 => 5
1 => 5
2 => 0
3 => 0
4 => 0
...
31 => 0
32 => 0
]

Added this Controller full code

public function index(Choice $choice){

    $duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get();
    $choices = Choice::where('user_id',Auth::id())->pluck('question_number');
    $user = Choice::where('user_id','=',Auth::id())->first();
    if ($user === null) {
        $too = 0;
        return redirect()->route('choices.create');
    }
    else{
        $too = 1;
        return view('choices.index',compact('too','duplicates','choices'));
    }
}

Full code of View

<table align="center" border="1" cellpadding="1" cellspacing="1" style="height:106px; width:100%">
    <thead>
        <tr>
            <th colspan="5" scope="col">
            <h3 style="text-align: center;"><b>Шалгалтын цаг сонголт</b></h3>
            <select style="text-align: center;" name="time" class="form-control"> 
                    <option value="30:01">30 минут</option>
                    <option value="40:01">40 минут</option>
                    <option value="50:01">50 минут</option>
                    <option value="60:01">60 минут</option>
                    <option value="70:01">70 минут</option>
                    <option value="80:01">80 минут</option>
                    <option value="90:01">90 минут</option>
            </select></th>
        </tr>
        <tr>
            <th style="text-align: center;" scope="col">№</th>
            <th style="text-align: center;" scope="col">Нэр</th>
            <th style="text-align: center;" scope="col">Нийт асуултын тоо</th>
            <th style="text-align: center;" scope="col">Асуултын тоо</th>
            <th scope="col"></th>
        </tr>
    </thead>
    <tbody>
    @foreach (array_combine($duplicates->toArray(), $choices->toArray()) as $duplicate => $choice){
        <tr>
            <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
            <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
            <td style="text-align: center;">{{ $duplicate->total }}</td>
            <td style="text-align: center;">{{ $choice->question_number }}</td>
            <td><a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td>
        </tr>
    @endforeach
    </tbody>
</table>

brwanobr oawnbrnoawbn obrawnor bonb rwanobrwn obrawnobrw aonbanobnaowbonwab onbonawb onrwa onbr awnob rwnobrno rbawnorb noawbnorba nobrwaonbrwa

Upvotes: 2

Views: 2564

Answers (5)

sathish
sathish

Reputation: 1

Better Join all those tables and keeep it in a single variable .Then pass the joins on view with compact()on controller method.then,do the foreach by keeping one variable.This makes you clean and better.

Upvotes: 0

DsRaj
DsRaj

Reputation: 2328

1 solution

You are using the choice id in the blade file but on the query, you are not loading the id So need to load the id and question_number both

$choices = Choice::where('user_id',Auth::id())->get(['id','question_number'])->toArray();

Also when you use toArray() you need to change the

From {{ $choice->question_number }}

TO {{ $choice['question_number'] }}

same for the choices edit link href="choices/{{ $choice['id'] }}/edit"

Or just remove the toArray() from the query.

2 solution

Now if you want to load the choice along with the topic and you have topic id in the choice model

$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get(); // Id for this table is your question number or any realtion between the Question Model and Choice Model
$choices = Choice::where('user_id',Auth::id())->pluck('question_number','topic_id')->toArray();
return view('choices.index',compact('duplicates','choices'));


@foreach ($duplicates as $duplicate)
    <tr>
        <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
        <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
        <td style="text-align: center;">{{ $duplicate->total }}</td>
        <td style="text-align: center;">
             {{ isset($choices[$duplicate->topic->id]) ? $duplicate->topic->id : '' }}
        </td>
        <td>
        <a class="btn btn-default" href="choices/{{ isset($choices[$duplicate->topic->id]) ? $choices[$duplicate->topic->id] : '' }}/edit">Шинэчлэх</a></td>
    </tr>
@endforeach

Upvotes: 2

OneLiner
OneLiner

Reputation: 611

In your controller don't use toArray() if you want both items to be objects. The best way I know of to do this in the view is to use array_combine() if the objects are the same length.

Controller

$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get()->toArray();
$choices = Choice::where('user_id',Auth::id())->get()->toArray();
return view('choices.index',compact('duplicates','choices'));

View

@for($i=0; $i< count($duplicates); $i++){
   <tr>
        <td style="text-align: center;">{{ $duplicates[$i]['topic']['id'] }}</td>
        <td style="text-align: center;">{{ $duplicates[$i]['topic']['title'] }}</td>
        <td style="text-align: center;">{{ $duplicates[$i]['total'] }}</td>
        <td style="text-align: center;">{{ $choices[$i]['question_number'] }}</td>
        <td><a class="btn btn-default" href="choices/{{ $choices[$i]['id'] }}/edit">Шинэчлэх</a></td>
    </tr>
@endfor

The error you showed is from trying to access an array using object syntax:

{{ $choice->question_number }}

$choices = Choice::where('user_id',Auth::id())->pluck('question_number');

If that is the only problem, then just don't use toArray() on the collection and leave it as an object or use array syntax.

Upvotes: 1

Hamelraj
Hamelraj

Reputation: 4826

trying to access $choice->id out of foreach loop in your view

you have used pluck() in your controller

so in your view you can't use $choice->question_number

so you need to change controller query or you can use below

@foreach ($duplicates as $duplicate)
  @foreach ($choices as $choice)
  // here only can use like this
      {{ $choice }}
      //{{ $choice->question_number }}
    @endforeach           

// this $choice->id out of foreach loop
<a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td> 
@endforeach

or as @Mayuri Pansuriya said you need to change your controller query then you can access

$choices = Choice::where('user_id',Auth::id())->get();

then you can access in your view

<td style="text-align: center;">
       @foreach ($choices as $choice)
           {{ $choice->question_number }}
       @endforeach
</td>

Upvotes: 1

Mayuri Pansuriya
Mayuri Pansuriya

Reputation: 954

Try to replace

$choices = Choice::where('user_id',Auth::id())->pluck('question_number')->toArray();

with $choices = Choice::where('user_id',Auth::id())->get(); as when you pluck you won't get the key question_number and will get the error trying t o get property of undefined

Upvotes: 1

Related Questions