4

I'm new to laravel and I tried to clear the problem from here

I have controller like the following:

foreach($users as $user){
    $message[] = Model::where('id',$user->id)->get();
}
$data['tests'] = $message;
return View::make('user.index', $data);

My View is:

@foreach($tests['message'] as $test)
    id : {{$test->id}}
@endforeach

which gives me Undefined index: message

I had dump the the $data in the controller. my array is as shown below. I place the var_dump in the controller before the return statement. my var_dump($data) is showing:

    array(1) {
        ["tests"] => array(2) {
            [0] => object(Illuminate\ Database\ Eloquent\ Collection) #515 (1) { ["items":protected]= > array(2) {
                [0] => ["attributes": protected] => array(14) {
                    ["id"] => string(3) "12"....

        }
    }
            [1] => object(Illuminate\ Database\ Eloquent\ Collection) #515 (1) { ["items":protected]= > array(2) {
                [0] => ["attributes": protected] => array(14) {
                    ["id"] => string(3) "12"....

        }
    }
    }

what i'm doing wrong. please help me

Community
  • 1
  • 1
m2j
  • 1,152
  • 5
  • 18
  • 43

3 Answers3

4
@foreach($tests as $test)
//$test is an array returned by get query.
  @foreach($test as $item)
    id : {{$item->id}}
  @endforeach
@endforeach

get return array, if you want to return one element, use find() or first().

LF00
  • 27,015
  • 29
  • 156
  • 295
  • it works, Thanks @Kris Roofe... anyway, is it the correct way of passing the data, or i'm doing dump? – m2j Nov 22 '16 at 06:52
  • in your case, use the get() is the proper way prefer to first() and find(). – LF00 Nov 22 '16 at 06:54
2

Your $tests['message'] should be $tests because you have not define message in your controller.

$message = array();
foreach($users as $user){
    $message[] = Model::where('id',$user->id)->get();
}
$data['tests'] = $message;
return View::make('user.index', $data);

View

@foreach($tests as $test)
    id : {{$test->id}}
@endforeach
Nikhil Vaghela
  • 2,088
  • 2
  • 15
  • 30
2

Try this:

$users = App\User::all()
foreach($users as $user){
    $message[] = Model::where('id',$user->id)->get();
}
$data['tests'] = $message;
return view( 'user.index', compact('data') );

In views/user.index.blade.php

@foreach($data['tests'] as $test)
    id : {{$test->id}}
@endforeach
Kabelo2ka
  • 419
  • 4
  • 14