I have one to many relation tables. I want to insert child table data in array instead of rows.
Mobile.php
protected $fillable = ['mobile_id', 'mobile_name'];
public function models() {
return $this->hasMany(Model::class, 'mobile_id');
}
Model.php
protected $fillable = ['model_name', 'mobile_id'
];
public function model()
{
return $this->belongsTo(Mobile::class, 'mobile_id');
}
View
Mobile Name: <input type="text" name="mobile_name">
Models:
<input type="text" name="model_name[]">
<button class="add_model">Add Model</button>
Controller
public function create(Request $request, Mobile $mob){
$mob= new Mobile;
$mob->mobile_name = request('mobile_name');
for($i=0; $i < count(request('model_name')); $i++){
$models = new Model;
$models->model_name = request('model_name')[$i];
$mob->models()->save($models);
}
$mob->save();
}
It's creates a new row for each mobile models inserted. But I want those models inserted in a single column model_name
in an array line.
I tried
for($i=0; $i < count(request('model_name')); $i++){
Size::create([
'model_name' => request('model_name')[$i],
'mobile_id' => $mob->id
]);
But it is also not working.