Home > Back-end >  Adding element to an array of arrays
Adding element to an array of arrays

Time:10-21

I want to call Model::insert() on this array to insert multiple data at once

"person" => array:2 [▼
    0 => array:2 [▼
      "name" => "Person 1"
      "place" => "Place 1"
    ]
    1 => array:2 [▼
      "name" => "Person 2"
      "place" => "Place 2"
    ]
  ]

but the Model excepts a foreign key constraint department_id before it can be inserted into the DB. How do I add department_id to each array inside person array. Is there any other way apart from using for loops to iterate and placing it manually?

Result Array Should look like

"person" => array:2 [▼
    0 => array:2 [▼
      "department_id" => 1
      "name" => "Person 1"
      "place" => "Place 1"
    ]
    1 => array:2 [▼
      "department_id" => 1
      "name" => "Person 2"
      "place" => "Place 2"
    ]
  ]

CodePudding user response:

Update Person model and "department_id" to the $fillable array:

protected $fillable = [
    ...
    'department_id',
];

Would be something similar to this:

<?php

// app/Models/Person.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Person extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'place',
        'department_id', // add department_id
    ];

   ...

}

CodePudding user response:

I think there is no escaping loop here. You can use array_map here, but it also runs the loop internally.

Person::insert(array_map(function ($person) {
    $person['department_id'] = 1;
    return $person;
}, $persons));
  • Related