Janily
Janily

Reputation: 301

laravel 4 Call to a member function posts() on a non-object

I followed some tutorial on http://culttt.com/2013/05/13/setting-up-your-first-laravel-4-model/ and it just won't work. Here's what I tried:

Post model:

class Post extends Eloquent {

  protected $fillable = array('body');

  public function user()
  {
    return $this->belongsTo('User');
  }
}

Routes:

Route::get('/posts',function()
{
  // Create a new Post
  $post = new Post(array('body' => 'Yada yada yada'));
  // Grab User 1
  $user = User::find(1);
  // Save the Post
  $user->posts()->save($post);
});

User model:

/**
 * Post relationship
 */
public function posts()
{
  return $this->hasMany('Post');
}

For Post model, just simply creating a body column and a user_id column. But, when I browser, display errors: "Call to a member function posts() on a non-object"

Would anyone know what the problem here is?

Upvotes: 0

Views: 4117

Answers (1)

philipbrown
philipbrown

Reputation: 554

You need to create the User before you attempt to retrieve it from the database.

Try:

 // Create a User
 $user = new User;
 $user->username = 'username';
 $user->email = '[email protected]';
 $user->password = 'password';
 $user->password_confirmation = 'password';
 $user->save();

 // Create a new Post
 $post = new Post(array('body' => 'Yada yada yada'));
 // Grab User 1
 $user = User::find(1);
 // Save the Post
 $user->posts()->save($post);

Upvotes: 2

Related Questions