qwerty
qwerty

Reputation: 5246

Laravel one-to-many relationship returns null

So here's what i have set up. I have two tables; users and todos. Every user can have multiple "todos".

Here's what the tables look like:

Users: enter image description here

Todos: enter image description here

And the models:

class User extends Eloquent 
{
    public function todo() {
        $this->has_many('todo');
    }
}

And...

class Todo extends Eloquent 
{
    public function user() {
        $this->belongs_to('user');
    }
}

Note that i already have a "todo" attached to the user in the database. So, with that said, should i not be able to do the following:

$user = User::find(1)->todo;

To get the todo's for that user? I'm currently getting Null when dd()-ing it:

array(1) {
  ["todo"]=>
  NULL
}

So, any ideas? I tried removing belongs_to() from the Todo's model, because it shouldn't be needed right? Either way it makes no difference. Am i missing something?

Upvotes: 0

Views: 876

Answers (1)

William Cahill-Manley
William Cahill-Manley

Reputation: 2405

You need to return the relation objects, e.g.

class User extends Eloquent 
{
    public function todos() {
        return $this->has_many('Todo');
    }
}

Also note that relations that return an array (e.g. has_many, has_many_and_belongs_to) are typically named plural, so 'todos' versus 'todo.

Upvotes: 1

Related Questions