将嵌套数组从控制器传递到laravel中的视图

时间:2016-11-22 06:04:55

标签: php arrays laravel foreach

我是laravel的新手,我试图从 here

清除问题

我有以下控制器:

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

我的观点是:

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

给了我Undefined index: message

我已将$data转储到控制器中。我的数组如下所示。我将var_dump放在return语句之前的控制器中。我的var_dump($data)正在显示:

    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"....

        }
    }
    }

我做错了什么。请帮帮我

3 个答案:

答案 0 :(得分:4)

    <filter level="TraceEventType.Error" />  

获取返回数组,如果要返回一个元素,请使用find()或first()。

答案 1 :(得分:2)

您的$tests['message']应为$tests,因为您尚未在控制器中定义消息。

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

查看

@foreach($tests as $test)
    id : {{$test->id}}
@endforeach

答案 2 :(得分:2)

试试这个:

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

在views / user.index.blade.php

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