Take the 2-minute tour ×

I have several tables in my database. Blogs, Users, Posts, Tags are the main ones. Also I have linking tables: User_blogs, Blog_posts & Post_tags.

My question is how to use Laravel's classes and methods like belogs_to(), has_many(). I need someone shed light on it. I've read many articles and documentation, but I'm still confused.

share|improve this question
add comment

1 Answer

Generally laravel is smart enough to detect many-to-many relationships if you set up your tables properly Both table names should be not pluralized in the intermediate/pivot table so you should have Users, Blogs, Posts, Tags as your individual tables and User_Blog, Blog_Post, Post_Tag as your intermediate tables. In those tables the cols should properly reflect the tablename_id (in lowercase) so in User_Blog it should have 3 cols id, user_id, blog_id etc and so on for the other columns.

In your models you just need to set up the many-to-many relationships

class User extends Eloquent
     public function blogs()
         return $this->has_many_and_belongs_to('Blog');

And so on for each model. If changing the structure isn't an option then simply add the table name in the many-to-many relationship like so return $this->has_many_and_belongs_to('Blog', 'User_blogs');

share|improve this answer
I'd just like to add in that you will thank yourself later if you go ahead and adopt the standard Laravel ORM table naming convention now. ie: blogs, users, blog_user –  Collin James Mar 8 '13 at 19:31
I do not know why but it's asking me for columns: user_blogs.created_at & user_blogs.updated_at. Are those necessary? –  Ivanka Todorova Mar 15 '13 at 23:42
They are expected. Just put public static $timestamps = false; in your model to disable Laravel's built in timestamps. –  bgallagh3r May 16 '13 at 13:45
add comment

Your Answer


