Laravel 5.6上的数据格式

时间:2018-08-24 07:31:58

标签: laravel

我开始学习Laravel框架,对此我有些怀疑。

我有2种模式:客户和机会。 我想在机会/show.blade.php上显示客户名称,但是我从控制器上的客户表中检索到的数据格式存在问题。

我的OpportunityController上具有以下show函数:

public function show($id)
{
    $opportunity = Opportunity::find($id);

    $customerName = Customer::select('name')->where('id','=',$opportunity->customer_id)->first();

    return view('opportunities.show',compact('opportunity','customerName'));
}

我这样在show.blade.php上调用此变量:

{{ $customerName }}

但是它以这种格式显示客户名称:

Customer: {"name":"John"}

如何显示这样的客户名称:

Customer: John

谢谢!

4 个答案:

答案 0 :(得分:0)

模型返回的数据为Std Class Object,因此您可以像这样使用它:

{{ $customerName->name }}  // i.e. variable->column_name

它将打印John

如果您使用的是get()而不是first(),则必须使用array循环来迭代返回的Std Class Object变量foreach()

答案 1 :(得分:0)

您当前正在返回模型对象。因此,您必须指定要显示的属性。在您的情况下,您仅选择了名称。因此,请执行以下操作:

{{ $customerName->name }}

答案 2 :(得分:0)

以下查询从数据库中选择一行,但仍作为对象返回

Customer::select('name')->where('id','=',$opportunity->customer_id)->first();

因此查询结果将是一个转换为{"name":"John"}

的对象

如果您想要名称值,则可以在视图中使用{{ $customerName->name }}或将查询更改为以下内容以仅获取name列:

Customer::select('name')->where('id','=',$opportunity->customer_id)->first()->name;

答案 3 :(得分:0)

$customerName在这种情况下被视为对象,因此请尝试使用{{ $customerName->name }}获得name的值。

希望它可以为您提供帮助