【问题标题】:Can't access laravel eloquent property in blade file无法访问刀片文件中的 laravel eloquent 属性
【发布时间】:2021-06-20 10:04:37
【问题描述】:

我正在通过以下方式从控制器中检索数据:

public function show($id)
{
     $news = News::select('id','heading', 'body', 'image','category')->with('newsCategory')->where('id', $id)->first();
     return view('pages.news_details')->with('news', $news);
}

新闻模型是

public function newsCategory()
{
   return $this->belongsTo(Category::class, 'category');
}

我得到了成功的回应

{"id":1,"heading":"Fugiat veniam nons.",
"body":"lorem ipsum dolor sit amet",
"image":null,
"category":4,
"news_category":{"id":4,"title":"health care","created_at":null,"updated_at":null}}

但是,我试图在刀片文件中访问它。除news-category 外,所有属性均可访问。这是我尝试访问它的方式

$news->news_category->title

dd($news->toArray())返回

但它不起作用。我怎样才能以这种方式访问​​该属性?

【问题讨论】:

  • 关系是newsCategory 而不是news_category
  • dd($news->toArray());在返回视图并将其发布到问题之前
  • 添加了@JohnLobo
  • 试试 $news->newsCategory ->title
  • 哦..!那行得通。但是一个问题是 dd 中的 news_category 但为什么 newsCategory 有效?

标签: laravel laravel-7


【解决方案1】:

正如 cmets 中已经写的那样,您正在尝试访问错误的属性。

在您的 News 模型中,您定义了属性 newsCategory 而不是 news_category。所以属性news_category 不存在。

将 Blade 视图中的代码切换为

$news->newsCategory->title

...那么它应该可以工作。

【讨论】:

    【解决方案2】:

    将模型转换为数组或 json 时,laravel 会将关系名称转换为蛇形大小写。这就是为什么它显示为news_category

    在您的刀片文件中,您仍在处理 eloquent 对象,因此尚未将其转换为蛇盒。因此,在您的 php 代码中,您需要以 newsCategory 访问它,因为这就是定义关系的方式。

    您可以使用模型上的static snakeAttributes 属性控制此行为。

       \**
         * Indicates whether attributes are snake cased on arrays.
         *
         * @var bool
         */
        public static $snakeAttributes = false;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 2016-08-02
      • 2016-08-27
      • 2021-12-05
      • 2017-06-27
      • 1970-01-01
      相关资源
      最近更新 更多