Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing nested array from controller to view in laravel

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

like image 219
m2j Avatar asked Feb 06 '23 15:02

m2j


2 Answers

@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().

like image 84
LF00 Avatar answered Feb 08 '23 05:02

LF00


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
like image 33
Nikhil Vaghela Avatar answered Feb 08 '23 06:02

Nikhil Vaghela