In Migration Table:
Schema::create('passws', function (Blueprint $table) {
$table->increments('id');
$table->integer('regist_id')->unsigned()->nullable();
$table->foreign('regist_id')->references('id')->on('regists');
$table->string('age');
$table->timestamps();
});
}
Regist Model - Mass Assignment Defined.
public function pass(){
return $this->hasOne('App\Passw');
}
In Controller
$name = $request->name;
$task = Regist::whereName($name)->get();
foreach ($task as $tasks){
$passw1->regist_id = $tasks->id;
}
$passw1->age = $request->age;
$regist = new Regist();
$regist->pass()->save($passw1);
When i store data, only age is getting stored but regist_id stored as null, (no error message or nothing). Here i'm sure controller shows "regist_id" => 1
and "age" => 25
when i use dd($passw1);
regist_id is only not getting stores in DB table.
Where am i doing an error??
Try this
$name = $request->name;
$regist = Regist::whereName($name)->first(); //it will give you a Regist model
$regist->pass()->create([
'age' => $request->age
]);
If you have more than one Regist
for $name
then try this
$regists = Regist::whereName($name)->get(); //it will give you a collection of Regist model
foreach ($regists as $regist){
$regist->pass()->create([
'age' => $request->age
]);
}
Check document here https://laravel.com/docs/5.6/eloquent-relationships#the-create-method