How can I update an existing Eloquent relationship in Laravel 4?
Taylor Otwell's official answer is the following:
$account = Account::find(99);
User::find(1)->account()->associate($account)->save();
I couldn't find the associate() method in the official docs. So if someone else is looking for a solution to this. Here you go!
This is how i would have done it
//step 1
My migrations
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
class CreateUserDetailsTable extends Migration {
public function up()
{
Schema::create('user_details', function(Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned()->unique('user_id', 'user_details_user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->enum('gender', array('male', 'female'))->nullable();
$table->string('city')->nullable();
$table->date('date_of_birth')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::drop('user_details');
}
}
Then
//step 2
My base models
class UserDetail extends Eloquent {
protected $guarded = array();
protected $table = 'user_details';
public function user()
{
return $this->belongsTo('User');
}
}
class User extends Eloquent {
protected $table = 'users';
protected $guarded = array();
public function detail()
{
return $this->hasOne('UserDetail');
}
}
Then
//step 3
My Controllers - Updating user_details schema
//When Updating records i get the raw data from say an input
$detail = Input::all();
//then find the user
$user = User::find(1);
//then update the details
$detail = $user->detail()->update($detail);
//then respond back with the detail
Response::json($detail);
My Controllers - creating user_details schema
//again get data input from source, the source does not come with user id
$detail = Input::all();
//when creating new record
$detail = new UserDetail($detail);
$detail = $user->detail()->save($detail);
return Response::json($detail);
And thats it for creating and updating new records using Laravel 4's belongsTo relationships
Hey you can refer the laravel docs for the solution.
Link http://laravel.com/docs/4.2/eloquent#inserting-related-models
$account = Account::find(10);
$user->account()->associate($account);
$user->save();