Home > Software design >  How to store multidimensional array from laravel and blade in database?
How to store multidimensional array from laravel and blade in database?

Time:08-26

While i do this in laravel, it stores all the PricingFeature for as many PricingDetail objects created. Please help me to save features for particular PricingDetail. Also tell how to access the same in blade

foreach($request->pricing_title as $key=>$value){
            $pricing = new PricingDetail;
            $pricing->software_id=$software->id;
            $pricing->pricing_title=$request->pricing_title[$key];
            $pricing->pricing_amount=$request->pricing_amount[$key];
            $pricing->pricing_terms=$request->pricing_terms[$key];
            $pricing->save();
            foreach($request->pricing_title as $pt){
                $pricingfeatures = new PricingFeature;
                $pricingfeatures->pricing_details_id=$pricing->id;
                $pricingfeatures->pricing_features=json_encode($request->pricing_features);
                $pricingfeatures->save();
            }
        }

Form Pricing Details

Pricing Features table

CodePudding user response:

For that, you should use a relationship One to Many: https://laravel.com/docs/9.x/eloquent-relationships#one-to-many


Logic example:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class PricingDetail extends Model
{
    /**
     * Get the features for the pricing detail.
     */
    public function features()
    {
        return $this->hasMany(PricingFeature::class);
    }
}
foreach($request->pricing_title as $key=>$value){
    $pricing = new PricingDetail;
    $pricing->software_id=$software->id;
    $pricing->pricing_title=$request->pricing_title[$key];
    $pricing->pricing_amount=$request->pricing_amount[$key];
    $pricing->pricing_terms=$request->pricing_terms[$key];
    $pricing->save();

    // Changes
    $pricing->features()->save($request->pricing_features);
}

CodePudding user response:

You don't do any json_encode or something. Just cast the field you wanted to save as array in your model class as below.

PricingFeature.php

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

And then you can go ahead with your following code.

foreach($request->pricing_title as $key=>$value){
            $pricing = new PricingDetail;
            $pricing->software_id=$software->id;
            $pricing->pricing_title=$request->pricing_title[$key];
            $pricing->pricing_amount=$request->pricing_amount[$key];
            $pricing->pricing_terms=$request->pricing_terms[$key];
            $pricing->save();
            foreach($request->pricing_title as $pt){
                $pricingfeatures = new PricingFeature;
                $pricingfeatures->pricing_details_id=$pricing->id;
                $pricingfeatures->pricing_features=$request->pricing_features;
                $pricingfeatures->save();
            }
        }
  • Related