skip to Main Content

I had a question about creating an array based on the number that was requested.

For example, if the number requested is ‘5’, it will create a sequence in the array like this [001,002,003,004,005)

I’m using Laravel, I’ve been trying something like this and it doesn’t work.

foreach($request->jumlah as $jumlah) {
        $storedetail = new DetailAlat();
        $storedetail->id_alat = $storealat->id_alat;
        $storedetail->sub_id_alat = $jumlah;
        $storedetail->created_by = Session::get('username');
        $storedetail->save();
}

I hope someone in here can help me

The error is:

Call to a member function toArray() on string

2

Answers


  1. You can use the range() function to create an array with a sequence of numbers. However, to get the numbers in the format you want (001, 002, 003, etc.), you can use array_map() function with sprintf() to format the numbers.

    $number = 5;
    $sequenceArray = range(1, $number);
    
    $formattedArray = array_map(function($num) {
        return sprintf('%03d', $num);
    }, $sequenceArray);
    
    foreach($formattedArray as $num) {
        $storedetail = new DetailAlat();
        $storedetail->id_alat = $storealat->id_alat;
        $storedetail->sub_id_alat = $num;
        $storedetail->created_by = Session::get('username');
        $storedetail->save();
    }
    
    Login or Signup to reply.
  2. Here is a simplified version

    for ($i = 1; $i <= 5; $i++) {
        DetailAlat::create([
            'id_alat' => $storealat->id_alat,
            'sub_id_alat' => sprintf('%03d', $i),
            'created_by' => Session::get('username')
        ]);
    }
    

    But for this to work you need to define $fillable property

    class DetailAlat extends Model
    {
        protected $fillable = ['id_alat', 'sub_id_alat', 'created_by'];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search