3 months ago

How to save item that has items inside using eloquent

Posted 3 months ago by Jonjie

Hi guys, hope you're doing good and safe :)

I'm just thinking how do you guys save this kind of setup using eloquent.

I have a main table called product, then a product hasMany() options, then every option hasMany() option_items. Please see my screenshot below for my design draft and code.



<div class="row option-row">
	<div class="col-md-6">
		<div class="panel panel-default option-panel">
			<div class="panel-heading">
				<input type="text" name="option_name[]" class="form-control white-background" placeholder="Product Option Name (e.g. Add-on Sides or Add-on Desserts)">
			<div class="panel-body">
				<div class="form-group{{ ($errors->has('required')) ? ' has-error' : '' }}" style="margin-left: 0; margin-right: 0;">
					<label class="control-label">Required?</label>
					<select name="option_required[]" class="form-control">
						@foreach([1 => 'Yes', 2 => 'No'] as $key => $required_value)
							<option value="{{ $key }}">{{ $required_value }}</option>
						<span class="help-block">{{ $errors->first('required') }}</span>

				<div class="table-responsive">
					<table class="table">
								<th>Item Name</th>
								<th>Item Price</th>
							<tr class="item-row">
									<input type="text" name="option_item_name[]" class="input-sm form-control" title="Example: 1-Cup Ice Cream">
									<input type="text" name="option_item_price[]" class="input-sm form-control" title="Example: 5.00">
									<span class="btn btn-danger btn-sm delete-option-item" title="Remove">&times;</span>

					<span class="btn btn-info btn-ms add-option-item">Add Item</span>
					<span class="btn btn-danger delete-option">Delete Option</span>

		<span class="btn btn-default" id="addOption">Add Option</span>

Pseudo code:

foreach(request('option_name') as $option_name){
	$option = Option::create(...)

	foreach(request('option_item_name') as $option_item_name){
		$option_item = OptionItem::create(..);



  • When I save the option_items, how do I know that it belongs to their option? I mean when I save it, the items also saves to other options.

Please sign in or create an account to participate in this conversation.