Jonjie
3 months ago
1096
22
Eloquent

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.

Screenshot:

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>
			<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>
						@endforeach
					</select>
					@if($errors->has('required'))
						<span class="help-block">{{ $errors->first('required') }}</span>
					@endif
				</div>

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

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

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

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

		$option_item->option->attach($option);
	}
}

Problem

  • 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.