I have 2 models.
User:
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
public function group ()
{
return $this->belongsTo('Group');
}
}
And Group:
class Group extends Eloquent {
protected $table = 'groups';
}
The user table has a foreign key on the group
column which references the id
on the group table.
Schema may help
Schema::table('users', function ($table) {
$table->foreign('group')
->references('id')
->on('groups')
->onDelete('cascade');
});
When I try to get the group of a user using:
User::find(1)->group()->name
I get the error
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
Group Schema as requested:
Schema::create('groups', function ($table) {
$table->increments('id');
$table->string('name');
$table->integer('permission');
});
Here are some screens:
users table
groups table:
And the users table FK
EDIT
@Cryode solved it for me in a chat session. The problem was that I had conflicting names. The model method used the same name as the column name (group
). Simply changing the column name in the database solved the issue.
After helping through chat, the problem was that there was an existing column called
group
, and the relationship method was also calledgroup
, so the table column value was taking precedence over the relationship method.Renaming the relationship method, or the
group
column to something likegroup_id
are both suitable solutions (I'd suggest thegroup_id
route).Original answer:
You retrieve the group through a magic property, not directly from the method.
If you retrieve the
group()
method, it will return the relationship object, not perform any queries and fetch the relating object.Also, Eloquent will make assumptions as to what your foreign key column names are.
Group
would automatically translate to agroup_id
column. If you have an existing column calledgroup
, then you should specify that explicitly in your relationship:If you receive a "Trying to get property of non-object" error for the property
group
, then your relationship is not returning any results ($user->group
will beNULL
). At that point, you should make sure your relationship is set up properly (e.g. using the correct belongsTo, hasOne, hasMany, etc.), and ensure that you actually have a related entry in your database.