Passing a nested array from a controller for viewing in laravel

I am new to laravel and I tried to fix the problem from here

I have a controller as shown below:

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

My view:

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

what gives me Undefined index: message

I dumped $datain the controller. my array is shown below. I put var_dump in the controller before the return statement. my var_dump($data)shows:

    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 am I doing wrong. Please help me

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

get the returned array, if you want to return a single element, use find () or first ().

+4
source

$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

:

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

/user.index.blade.php

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

Source: https://habr.com/ru/post/1661544/


All Articles