Search code examples
phplaravellaravel-blade

Passing multidimensional array to blade using controller


I want to pass multidimensional Array to Blade file using Controller method:

        return view('msg.simple', [
            'message' => 'here is my message',
            'links' => [
               [
                    'title' => 'link title 1',
                    'url' => 'www.example.com'
               ],
               [
                    'title' => 'link title 2',
                    'url' => '#2'
               ]
            ]
        ]);

view file (blade):

@foreach($links as $link)
    <a href="{{$link->url}}">{{$link->title}}</a>
@endforeach

but it shows the following error:

htmlspecialchars() expects parameter 1 to be string, array given


Solution

  • Use this :

    $data = [
                'message' => 'here is my message',
                'links' => [
                    [
                        'title' => 'link title 1',
                        'url' => 'www.example.com'
                    ],
                    [
                        'title' => 'link title 2',
                        'url' => '#2'
                    ]
                ]
            ];
            return view('msg.simple',compact('data'));
    

    and in view file :

            @foreach($data['links'] as $link)
                <a href="{{$link['url']}}">{{$link['title']}}</a>
            @endforeach