首页 > 解决方案 > 在 laravel 的刀片中显示来自数据库的值

问题描述

<option>标签内,我试图从数据库中添加选定的国家。

<option>
{{ Auth::user()->cpreference()->where('qatype',1)->select('country')->first()}}
</option>

下拉列表中显示的输出如下:

{"country":"Algeria"}

我如何只显示国家名称?

标签: phplaraveleloquentlaravel-blade

解决方案


访问返回的模型对象的属性

<option>
{{ \Auth::user()->cpreference()->where('qatype', 1)->select('country')->first()->country }}
</option>

并且对刀片视图进行查询不尊重 MVC 架构中的关注点分离

您应该User像这样向模型添加访问器

public function getCountryAttribute()
{
   return $this->cpreference()->where('qatype', 1)->select('country')->first()->country;
}

并在你的视野中打出更优雅的电话

<option>{{ auth()->user()->country }}</option>

希望这可以帮助


推荐阅读