I am making user to user messaging system in laravel 4. So in a simplified version i have to table
First table
Users
user_id |
user_name
Second table
Messages
message_id |
message_from_user_id |
message_to_user_id |
message_content |
So after reading the documentation I learned that User has many message and message belongs to User.
But how do I actually relate them in coding?
I am quite confused how will I use the foreign key in this case for a message that will have two user?
Check this out: http://laravel.com/docs/eloquent#many-to-many
Basically you need a table structure like this
Users: id | username
Messages: id | from | content
user_messages: user_id | message_id
You can define your models like this
class User extends Eloquent {
public function messages()
{
return $this->belongsToMany('Message');
}
public function sent_messages()
{
return $this->hasMany('Messages', 'from');
}
}
class Message extends Eloquent {
public function from()
{
return $this->belongsTo('User', 'from');
}
public function to()
{
return $this->belongsToMany('User');
}
}