Defining has one relationship with Laravel

Solution:

So here’s the relationship:

  • An Order has many Negotiations.
  • A negotiation belongs to an order.

I think Laravel couldn’t make it any more simpler to specify relationships, because it’s almost exactly how you speak it:

class Order extends Eloquent 
{
    public function negotiations() 
    {
        return $this->hasMany('Negotiation');
    }
}

class Negotiation extends Eloquent 
{
    public function order() 
    {
        return $this->belongsTo('Order');
    }

}

And that’s it. And, of course, with this kind of relationship you need to specify the foreign keys in your tables / migrations:

Schema::create('orders', function(Blueprint $table)
{
    $table->integer('id');
    $table->string('number',64);
});

Schema::create('negotiations', function(Blueprint $table)
{
    $table->integer('id');
    $table->integer('order_id'); //here it is
    $table->string('subject');
    // ... and so on
});

And that’s really all there is to it.