0

Can't parse array to view.

Here is the array

 Array (
    [positions] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [company_id] => 1
                    [title] => Software Developer
                )

            [1] => Array
                (
                    [id] => 2
                    [company_id] => 2
                    [title] => Accountant
                )

            [2] => Array
                (
                    [id] => 3
                    [company_id] => 3
                    [title] => Insurance salesman
                )
        )
)

this is the controller

$data = array(
    'positions' => $newarray['data']
);
return view('mypage', $data);

and this is the view where i try to echo the title

@foreach($positions as $position)
{{ $position->title }}<br>
@endforeach

i get this error in the view "Trying to get property of non-object"

Priya
  • 1,359
  • 6
  • 21
  • 41
Edvard Åkerberg
  • 2,181
  • 1
  • 26
  • 47

3 Answers3

2
@foreach($positions as $position)
  {{ $position['title'] }}<br>
@endforeach
aldrin27
  • 3,407
  • 3
  • 29
  • 43
  • I don't know why are you getting upvotes, but your code will definitely won't work for two reasons. Because OP passes `$data` array in the view and he has broken code anyway. – Alexey Mezenin Apr 29 '16 at 10:03
  • The code is almost OK. But what will happend if key does'nt exists? I made small change in your code. – Filip Koblański Apr 29 '16 at 11:04
0

I've answered similar question here, but if it'll be helpful, here it is.

@foreach($data['positions'] as $position)
{{ $position['title'] }}<br>
@endforeach

Also, you should change:

$data = array(
    'positions' => $newarray['data']
);

to something like:

$data = array(
    'positions' => $someDataArray;
);
Community
  • 1
  • 1
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

First of all format your array properly, like this:

$positions = array
(
    array(
        'id' => 1,
        'company_id' => 1,
        'title' => 'Software Developer'
    ),
    array(
        'id' => 2,
        'company_id' => 2,
        'title' => 'Accountant'
    ),
    array(
        'id' => 3,
        'company_id' => 3,
        'title' => 'Insurance salesman'
    )
);

Pass data to view:

$data = array(
    'positions' => $positions
);
return view('mypage', $data);

Now you can echo title like following:

@foreach($positions as $position)
    {{ $position['title'] }}<br>
@endforeach
Sovon
  • 1,804
  • 1
  • 22
  • 30