简体   繁体   中英

Laravel - Save multiple fields as array instead of row

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.

You should serialize the data before saving it in the database.Create the model instance outside the for loop.Here is the working code.

   public function create(Request $request, Mobile $mob){
      $mob= new Mobile;
      $mob->mobile_name = $request('mobile_name');
      $models = new Model;
      $arr=[];
      for($i=0; $i < count($request('model_name')); $i++){
         array_push($arr, $request('model_name')[$i]);
         }
      serialize($arr);
      $models->model_name =$arr;
      $mob->models()->save($models);
     $mob->save();
    }

In the model.php, add the below code

protected $casts = [
      'model_name ' => 'array',
]

I think the problem is your schema table, because you need to achieve this first :

//  Migrations 
$table->json('model_name');

That way you can persist many model_name in one row using one array.

Try this 100% working i have deployed .

foreach($request->model_name as $item => $value)
$data[$value]=array(
    'mobile_name'=>$request->mobile_name,
    'model_name'=>$value,
    
);

Mobile::insert($data); // Eloquent approach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM