简体   繁体   English

Laravel-从控制器传递数组到视图

[英]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. 变量本身可以很好地传递,我可以使用var_dump来查看数组的内容。 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. 因此,到目前为止,我能够var_dump $ user数组,并且可以正常工作,但是,当我尝试回显数组的一部分时,我得到了未定义的索引,即使我知道事实“名称”是我的索引之一。 I've also tried $user[1] and get got the same error. 我也试过$ user [1]并得到同样的错误。

var_dump output var_dump输出

array(1) {
    [0]=> object(stdClass)#148 (11) {
        ["id"] => int(1)
        ["name"]=> string(9) "paul rudd"
        ["email"]=> string(18) "email@email.com"
        ["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"
    }
}

Based on your var_dump output try; 根据您的var_dump输出尝试;

<?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; 在原始查询中,特别是挑选一个id时,最好先获得第first结果,而不要像这样使用get

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

Notice the ->first() then you can simply do; 注意->first()然后您可以简单地完成;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM