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

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}}
Last updated 10 years ago.
0

@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 10 years ago.
0

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.

0

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.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

DevHack devhack Joined 19 Nov 2014

Moderators

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

Your logo here?

Laravel.io

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

© 2024 Laravel.io - All rights reserved.