Peter Jewicz
Peter Jewicz

Reputation: 666

Laravel - Passing array from Controller to view

I'm having an issue passing a variable from a database query to my view. The variable itself passes fine, and I can var_dump it to see the contents of the array. The problem is when I try to call a part of the array, I get an undefined index error.

Controller:

public function displayCustomer()
    {
        $id = $_GET['id'];

$user = DB::table('customers')->where('id', '=',  $id)->get();


                return View::make('single')->withuser($user);

} 

View

<body>
 <?php
    if (Auth::check() != TRUE)
    {
       return Redirect::guest('login')->with('failed', 'Login Failed');
    }
?>


<?php
//var_dump($user);
echo($user['name'])
?>



</body>

So as of right now, I'm able to var_dump the $user array and it works fine, However, when I try to echo out a part of the array I get undefined index, even though I know for a fact 'name' is one of my indexes. I've also tried $user[1] and get got the same error.

var_dump output

array(1) {
    [0]=> object(stdClass)#148 (11) {
        ["id"] => int(1)
        ["name"]=> string(9) "paul rudd"
        ["email"]=> string(18) "[email protected]"
        ["phone"]=> string(10) "6305555555"
        ["address"]=> string(15) "123 fake street"
        ["item"]=> string(13) "6 pcs"
        ["total_price"]=> float(500)
        ["paid_amount"]=> float(400)
        ["balance"]=> float(100)
        ["created_at"]=> string(19) "0000-00-00 00:00:00"
        ["updated_at"]=> string(19) "0000-00-00 00:00:00"
    }
}

Upvotes: 0

Views: 6770

Answers (1)

Gary Green
Gary Green

Reputation: 22395

Based on your var_dump output try;

<?php echo $user[0]->name; ?>

Your user is an array of objects. In your original query as your specifically picking out one id it might be better to get the first result instead of using a get, like so;

$user = DB::table('customers')->where('id', '=',  $id)->first();

Notice the ->first() then you can simply do;

<?php echo $user->name; ?>

Upvotes: 4

Related Questions