简体   繁体   中英

How do I save array of data from laravel blade to database

I have this dumped output from the Laravel blade. In this, you can notice there is an array of amounts of data. Now, How do you save all the data, including an array, to the database?

Data From Form blade

array:9 [▼
  "_token" => "JjZqQiTv304JU65DNCli4MSjOsO0aqB84KVu8UgB"
  "category" => "Equestrian"
  "logistics" => "Barloworld"
  "currency" => "USD"
  "descriptions" => "Dolore labore cillum"
  "user_id" => "33"
  "m_description" => "Test"
  "ddate" => "2021-07-08"
  "amount" => array:2 [▼
    0 => "300"
    1 => null
  ]
]

Controller

        $data = $request->all();
        dd($data);
         $data = new Order();
        
         $data->amount = $request->get('amount');
         $data->m_description = $request->get('m_description');
         $data->ddate = $request->get('ddate');
         $data->currency = $request->get('currency');
         $data->descriptions = $request->get('descriptions');
         $data->logistics = $request->get('logistics');
         $data->category = $request->get('category');
         $data->code = $request->get('code');
         $data->user_id = $request->get('user_id');
         $data->save();

To save array you will have to use JSON format. Sometimes, you can use pivot tables to solve this problem but it has no sence to have pivot table for amount.

$data->amount = json_encode($request->get('amount'));

When getting data from database, you can make cast on model, or method which will return json_decode($this->amount)

If you would provide more information about what exactly could be in amount, I could answer better.

I think you can use model casting for array store in database

refer this link

https://laravel.com/docs/8.x/eloquent-mutators#array-and-json-casting

    protected $casts = [
            'amount' => 'array',
        ];

You can turn the data into a string by using either json_encode($array) or serialize($array) . And then save the string to your database.

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