G
G
GaserV2016-09-29 17:52:31
Laravel
GaserV, 2016-09-29 17:52:31

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

  }

Post Model:
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');
  }


}

RESOLVED! We thank you very much simply)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2016-09-29
@GaserV

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.

E
Evgeny Perin, 2016-09-29
@seoperin

Look at the docks by link

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question