Laravel belongsTo not working

Maybe there's an issue with Eloquent finding the foreign key. Try this:

class User extends Eloquent {

    public function medicine_type()
    {
        return $this->belongsTo('MedicineType', 'medicine_type_id');
    }
}

EDIT:

Also, Eloquent tries to find the table "medicinetypes" and not "medecine_types", so you need to specify that as well using the $table variable.

class MedicineType extends Eloquent {
    protected $table = 'medicine_types';

    public function users()
    {
        return $this->hasMany('User');
    }
}

The reason your relation is not working is not because of the relations specified in the model, but because of the method naming in the User model and not specifying the foreign key.

Instead of:

public function medicine_type()
{
    return $this->belongsTo('MedicineType');
}

Use:

public function medicineType()
{
    return $this->belongsTo('MedicineType', 'id');
}

I hope this works for you ;)

Everything together:

<?php // app/models/MedicineType.php

class MedicineType extends Eloquent {

   // Determines which database table to use
   protected $table = 'medicine_types';

   public function users() 
   {
      return $this->hasMany('User');
   }

}

and:

<?php // app/models/User.php

class User extends Eloquent {

   // Determines which database table to use
   protected $table = 'users';

   public function medicineType() 
   {
      return $this->belongsTo('MedicineType', 'id');
   }

}

Testing if it works:

$user = User::find(1);
return $user->medicineType->name;

This successfully returns the related medicine_type's name.

I hope this helps you further ;)


I made the stupid mistake of not adding the "return" in the relationship method!

Make sure you return the relationship... Obviously this will not work:

public function medicineType() 
   {
      $this->belongsTo('MedicineType', 'id');
   }

I change "medicine_type" to "medicineType" and everythings got OK...