Support the ongoing development of →
Database Eloquent
Last updated 2 years ago.

I would go this way
First please!.... Name the model SAME as the table name.
I would not create username field again in blogs table.

Blogs Table (Blog model)

Schema::create('blogs', function(Blueprint $table)

In your User model

public function blog()
   return $this->hasMany('Blog')

In your Blog model

public function user()
   return $this->belongsTo('User')

Now the Blog is in relation to User, so whenever User change the name, you can access the username for the blog by

{{ $blog->user->username}}
Last updated 9 years ago.

@Torchsk, It's not about fetching bro. I am asking about update, ? i.e, if i update user table, will it auto update blog table with modified username. ?

Last updated 9 years ago.

No it won't. As TorchSK mentioned, you should use the users ID rather than their username. From what you have said, a user seems to be able to change their username, where as the users ID will never change, so use that to refer to a user in other tables.


Well yeah.. i was bit in a hurry so I did not explain myself...
But as shabushabu said, it is better to reference to user ID instead of username, while ID never change...

If there is not a special reason why to have username attribute also on Blog, it is better no to.

You can always use "User's username" as "Blog's username" as each Blog belongs to user.


Sign in to participate in this thread!


Your banner here too?

DevHack devhack Joined 19 Nov 2014


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 - All rights reserved.