phparrayslaravellaravel-bladelaravel-8

I keep getting this error "Cannot access offset of type string on string" whenever I try to serve dummy data to my Laravel application


I am trying to serve some data to my view. However, when i try to access the elements in my dummy array, i keep getting an error "Cannot access offset of type string on string". And I don't know what is causing this error. I'm quite new to PHP so I need assistance.

This is the data I'm trying to serve

Route::get('/', function () {
    return view('home', [
        'jobs' => [
            'title' => 'Influencer',
            'salary' => '790,340'
        ],
        [
            'title' => 'Farmer',
            'salary' => '560,890'
        ],
        [
            'title' => 'Doctor',
            'salary' => '760,881'
        ],
        [ 
            'title' => 'Engineer',
            'salary' => '1,247,122'
        ]
    ]);
});

This is the view I'm trying to populate

<x-layout>
    <x-slot:heading>
        Home Page
    </x-slot:heading>

    @foreach ($jobs as $job)
        <li>{{ $job['title'] }}</li>
    @endforeach
</x-layout>

Solution

  • The problem is that array of jobs is not structured properly.You need to ensure that the all array element of jobs are wrapped in main array closure(i.e. []). Use this instead.

    Route::get('/', function () {
        return view('home', [
            'jobs' => [
                [
                    'title' => 'Influencer',
                    'salary' => '790,340'
                ],
                [
                    'title' => 'Farmer',
                    'salary' => '560,890'
                ],
                [
                    'title' => 'Doctor',
                    'salary' => '760,881'
                ],
                [ 
                    'title' => 'Engineer',
                    'salary' => '1,247,122'
                ]
            ]
        ]);
    });