rushtoni88
rushtoni88

Reputation: 4665

Accessing a property on a method which returns a Model in Laravel

I have a Post model which has a function as follows:

namespace App;

use App\Category;

class Post extends Model

{
    public function category()
   {

    return $this->hasOne(Category::class);

   }

}

And my Category Model looks like this

namespace App;

use App\Post;

class Category extends Model
{
    public function posts()
    {

    return $this->hasMany(Post::class);

    }
}

In my view, I want to get access to the name field on the category for each post.

I assumed I would have access to that model and could therefore get it by doing this in my blade file:

{{ $post->category()->name }}

$post is correct, I have access to other properties but this throws the error:

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$name

Any ideas?

Upvotes: 1

Views: 1346

Answers (2)

Laerte
Laerte

Reputation: 7083

You should access it as an attribute:

{{ $post->category->name }}

The function category() should be defined in Post model as:

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

If category_id has another name, just change it in the parameter.

Upvotes: 3

Siavosh Djazmi
Siavosh Djazmi

Reputation: 21

you can easily do this:

$category=$post->category;
$cat_name=$category->name;

also if you only want the name field of the category you can use :

$cat_name=$post->category()->get(['name']);

Upvotes: 1

Related Questions