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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21639536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:59:34  来源:igfitidea点击:

Laravel - Passing array from Controller to view

phparrayslaravellaravel-4

提问by Peter Jewicz

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.

我在将变量从数据库查询传递到我的视图时遇到问题。变量本身通过得很好,我可以通过 var_dump 来查看数组的内容。问题是当我尝试调用数组的一部分时,出现未定义的索引错误。

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.

所以到目前为止,我可以对 $user 数组进行 var_dump 并且它工作正常,但是,当我尝试回显数组的一部分时,我得到了未定义的索引,即使我知道一个事实 'name' 是我的索引之一。我也试过 $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 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"
    }
}

回答by Gary Green

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 firstresult instead of using a get, like so;

您的用户是一组对象。在您的原始查询中,因为您专门挑选了一个 id,所以获得first结果而不是使用 a可能会更好get,就像这样;

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

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

注意->first()then 你可以简单地做;

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