【问题标题】:Showing a value from the DB in a blade in laravel在 laravel 的刀片中显示来自数据库的值
【发布时间】:2020-02-03 19:24:25
【问题描述】:

<option> 标记内,我正在尝试从数据库中添加选定的国家/地区。

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

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

{"country":"Algeria"}

如何只显示国家名称?

【问题讨论】:

    标签: php laravel eloquent laravel-blade


    【解决方案1】:

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

    <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>
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      这样做:

      Auth::user()->cpreference()->where('qatype',1)->select('country')->first()
      

      你得到了整个对象,并且考虑到你试图输出它的事实,它被转换为json

      要访问特定属性的值,只需在末尾添加-&gt;country

      Auth::user()->cpreference()->where('qatype',1)->select('country')->first()->country
      

      作为旁注,我建议您避免在前端进行查询,您可以在控制器中获取值,然后将它们发送到视图。此外,为了避免这种长查询,您可以在模型中定义 AccessorsLocal Scopes。查看文档以获取更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-31
        • 2022-08-14
        • 1970-01-01
        • 2020-07-10
        • 2020-08-19
        • 2021-01-07
        • 2019-07-16
        相关资源
        最近更新 更多