Search code examples
laravellaravel-7

Can't access laravel eloquent property in blade file


I'm retrieving data in following way from controller:

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);
}

News model is

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

and I got a successful response

{"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}}

However, I trying to access it in blade file. All the properties are accessible except news-category. Here how I'm trying to access it

$news->news_category->title

dd($news->toArray()) returns

enter image description here

But it's not working. How can I access the property in that way ?


Solution

  • When converting the model to array or json, laravel converts relationship names to snake case. That is why it is being shown as news_category.

    In your blade file, you are still dealing with the eloquent object, so it hasn't been converted to snake case yet. Thus in your php code, you need to access it as newsCategory as that is how the relationship has been defined.

    You can control this behaviours using the static snakeAttributes property on the model.

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