Laravel relationships

Trying to figure what table I need to make this relationship to work...

I'd like the user to mark a post as favorite and save it so when he log back in, he can view all his favorite posts.

So I have User and Post models and their relationships of course.

User hasMany Post, Post belongTo User

Do I need to add Favorite model and add fav_id to both User and Post models ? Or maybe adding pivot table?


If a favorite is defined as a simple relationship between users and posts, you don't need a model for it. However, you do want a pivot table, call it something like favorites. It would contain id, post_id, user_id, created_at, updated_at.

Then in your user model:

public function favoritePosts()
  return $this->belongsToMany('Post', 'favorites');

And in the post model:

public function favoritedBy()
  return $this->belongsToMany('User', 'favorites');

So now, for any given user, you can do $user->favoritePosts to get an array of posts that user has "favorited".

And from a post object, you can do $post->favoritedBy, to get an array of users that have favorited that post.

I haven't tested this but that seems like that would work off the top of my head.

Need Your Help

Why does incrementing a void pointer by 1 moves one byte ahead but it's 4 bytes for an integer pointer,8 for double?

c pointers void-pointers pointer-arithmetic

In the following program,if I add 1 to a void pointer, it moves one byte ahead.But,quite as expected, it moves 4 and 8 bytes respectively for int and double pointers.Why does the void pointer move...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.