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();
}
}
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);
}
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();
}
}
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.