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.
So...
Blogs Table (Blog model)
Schema::create('blogs', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title');
$table->longtext('message');
$table->timestamps();
});
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}}
@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. ?
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!
The Laravel portal for problem solving, knowledge sharing and community building.
The community