Support the ongoing development of Laravel.io →
Input Database Eloquent

Hello

I'm learning Laravel 4, and I came up to Eloquent relationships. I have two models, user and group. Users can have many groups and group belongs to one user. I've setup the relationships following tutorials from Tuts+, but for some reason user_id is not saved in groups table. Table users contains id, username, email, password and timestamps Table groups contains id, user_id, title, description, shared (boolean) and timestamps

And this is my code:

// group model
class Group extends Eloquent {
	protected $guarded = array();

	public function user(){
		return $this->belongsTo("user", "user_id");
	}

	public static $rules = array(
		"title" => "required"
	);
}

// user model
...
public function groups(){
	return $this->hasMany("group");
}

// controller method for saving groups
public function postGroup(){
	$validate = Validator::make(Input::all(), Group::$rules);
	if($validate->passes()){
		User::find(2)->groups()->insert([
			"title" => Input::get("title"),
			"description" => Input::get("description")
		]);

	}else{
		return "error";
	}
}

In users table I created user with id 2. So everything saves in groups table except user_id. Can someone help me?

Last updated 2 years ago.
0

have you tried using create instead of insert?

Last updated 2 years ago.
0

alainbelez said:

have you tried using create instead of insert?

Create works, thank you

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

alenn-m alenn-m Joined 5 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.