Ajmal Razeel
Ajmal Razeel

Reputation: 1701

Passing array from controller to view in Laravel

I am new to Laravel and trying to pass a one dimensional array from controller to the view.

This is my controller function

 public function onedim_array()
    {
        $info = array(
            'firstname' => 'John',
            'lastname' => 'Cena',
            'from' => 'USA'
            );

        return view('one_dim_array',  compact('info'));
    }

This is my view file:

<?php

foreach($info as $i)
{
    echo $i['firstname'];
}

?>

It gives me the following error:

ErrorException in 34a7177cfbceee0b4760125499bdaca34b567c0b.php line 5: Illegal string offset 'firstname' (View: C:\AppServ\www\blog4\resources\views\one_dim_array.blade.php)

I don't know where I am making mistake. Please Help

Upvotes: 3

Views: 7041

Answers (3)

aceraven777
aceraven777

Reputation: 4556

I think you're expecting to accept multidimensional array to the view. I think here's the value of the array you're expecting to pass to the view

Controller code:

public function onedim_array()
{
    $info = array(
        array(
            'firstname' => 'John',
            'lastname' => 'Cena',
            'from' => 'USA'
        ),
        array(
            'firstname' => 'John',
            'lastname' => 'Doe',
            'from' => 'Canada'
        ),
    );

    return view('one_dim_array',  compact('info'));
}

PS. Suggestion before diving to study a framework: "Master the basics of PHP first", and learn how to debug.

Upvotes: 0

a.smaliankou
a.smaliankou

Reputation: 1

foreach() allow you to traverse all items in your array. And in your code snippet

<?php

foreach($info as $i)
{
    echo $i['firstname'];
}

?>

you try to get element with index 'firstname' from a string (in your example it will be 'John'). If you want traverse all elements and display them, try this:

foreach($info as $i)
{
    echo $i;
}

or if you want to display specific element of your array, try this

echo $info['firstname'];

or

echo $info['lastname'];

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163968

Since it's not multidimensional array, use this instead of foreach():

$info['firstname']

Upvotes: 7

Related Questions