Answer the question
In order to leave comments, you need to log in
How to display the category name correctly?
Good afternoon. Such situation. There is a posts() method:
public function posts()
{
$posts = Post::orderBy('id','desc') -> get();
return view('admin/posts', compact('posts'));
}
class Post extends Model
{
public $timestamps = false;
protected $table = 'posts';
protected $fillable = ['','title','content','image','category','date'];
public function category()
{
return $this->hasOne('App\Category', 'id', 'category_id');
}
}
Answer the question
In order to leave comments, you need to log in
First, always use the singular form of model names. For example: "Post", "Category", "Action", "User" and so on.
Secondly, in the Post model, you must use $this->hasOne, which literally means "has one". The post has a category, right? So write. You write "belongsTo", that is, "belongs" - so does the category post belong? That is, a category has a post, and not a post has a category? Of course not, a post has a category, and a category cannot belong to one post, so the category should (optionally) have a method "posts() { return $this->belongsToMany(Post::class); }" .
And in general - read the documentation. Read well, and you can still buy a subscription to laracasts.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question