Reputation: 4665
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
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
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