Q:

Please explain the foreign_key and local_key in Laravel ORM relationships

I'm effectively trying to define the relationships between users (sender and recipient) and messages.
My Messages migration is:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMessagesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('messages', function($t){
            $t->increments('id');
            $t->integer('sender_user_id')->unsigned();
            $t->integer('recipient_user_id')->unsigned();
            $t->string('subject');
            $t->text('content');
            $t->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::dropIfExists('messages');
    }

}

My Message model was straightforward:
<?php

class Message extends Eloquent{
    // link to sender user id
    public function from(){
        return $this->hasOne('User', 'sender_user_id'); 
    }
    // link to recipient user id
    public function to(){
        return $this->hasOne('User', 'recipient_user_id');
    }
}

But I'm unsure in defining the hasMany relationships in my User model.
The docs (http://laravel.com/docs/eloquent#relationships) shows the following:
return $this->hasMany('Comment', 'foreign_key');

return $this->hasMany('Comment', 'foreign_key', 'local_key');

Now, I'm confused which key is which in the latter hasMany relationship. Which is correct for my User model?
public function sentMessages(){
    return $this->hasMany('Messages', 'id', 'sender_user_id');
}

public function sentMessages(){
    return $this->hasMany('Messages', 'sender_user_id', 'id');
}

A:

You have to set your relation like this:
public function sentMessages()
{
    return $this->hasMany('Messages', 'sender_user_id');
}

public function receivedMessages()
{
    return $this->hasMany('Messages', 'recipient_user_id');
}

