У меня есть следующие модели:
Page.php и Content.php в отношении один ко многим.
Их структура таблицыследующим образом:
страниц
id |название |слаг
содержимое
id |page_id |section_title |section_content
В моем представлении редактирования поля section_title
и section_content
могут создаваться динамически.
т.е.: пользователь может добавить дополнительные разделы для контента, если он этого хочет.
Ниже приведен фрагмент страницы редактирования:
@foreach ($page->content as $content)
<div class="row fieldGroup" id="dataRow{{$content->id}}">
<input type="hidden" name="contentID[]" value="{{$content->id}}">
<div class="col-sm-10 ">
<div class="form-group floating-label {{$errors->has('sectionTitle') ? 'has-error' : ''}}">
<input type="text" name="sectionTitle[]" id="sectionTitle" class="form-control" value="{{$content->sectionTitle}}"> @if($errors->has('sectionTitle'))
<span class="help-block">{{ $errors->first('sectionTitle') }}</span> @endif
<label for="sectionTitle">Section Title</label>
</div>
</div>
<div class="col-sm-2 ">
@if($loop->first)
<a href="javascript:void(0)" class="btn btn-success addMore">
<span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add Section
</a>
@else
<a href="javascript:void(0)" class="btn btn-danger removeData" id="id-delete" data-id="{{$content->id}}"><span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</a> @endif
</div>
<div class="col-sm-12 ">
<div class="form-group">
<h4>Section Content</h4>
<textarea name="sectionContent[]" class="editor">{{$content->sectionContent}}</textarea>
</div>
</div>
</div>
@endforeach
А ниже приведен фрагмент метода обновления с контроллера:
$page - > title = $request - > title;
$page - > slug = Str::slug($request - > title, '-');
$page - > save();
$contents = Content::where('page_id', $page - > id) - > get();
for ($i = 0; $i < count($request - > sectionTitle); $i++) {
foreach($contents as $db) {
if (isset($request - > contentID[$i]) && $db - > id == $request - > contentID[$i]) {
$content = Content::find($request - > contentID[$i]);
$content - > sectionTitle = $request - > sectionTitle[$i];
$content - > sectionContent = $request - > sectionContent[$i];
$content - > save();
} else {
$new = new Content;
$new - > page_id = $page - > id;
$new - > sectionTitle = $request - > sectionTitle[$i];
$new - > sectionContent = $request - > sectionContent[$i];
$new - > save();
}
}
}
Проблема в том, что пользователь нажимает кнопку обновления после редактирования содержимого.Каждое содержимое сохраняется более одного раза.
т.е.: если имеется 3 содержимого, то каждое содержимое сохраняется 3 раза