You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 7中动态表单数据存储更新及响应式按钮修复技术求助

Solution to Your Dynamic Form & Responsive Button Issues

Let's break down and fix your two main problems step by step:

1. Fixing Dynamic Form Data Saving/Updating

Your current code has a few key issues preventing proper saving/updating of the link data:

A. Correct Validation Rules

Your validation was targeting title and link directly, but your form inputs are nested in an array (links[...][title]). Update your controller validation to target array elements:

public function store(Request $request)
{
    // Fix validation to target the array of links
    $this->validate($request, [
        'links.*.title' => 'required',
        'links.*.link' => 'required',
    ]);

    $links = collect([]);

    if ($request->links) {
        foreach ($request->links as $link) {
            // Use the link ID (if present) to update existing records, not just title
            $model = Link::updateOrCreate(
                ['id' => $link['id'] ?? null], // Match existing record by ID
                ['title' => $link['title'], 'link' => $link['link']]
            );
            $links->push($model);
        }
    }

    // Delete links that were removed from the form
    Link::whereNotIn('id', $links->pluck('id'))->delete();

    return redirect()->back()->with('success', 'لینک ها با موفقیت ذخیره شدند');
}

Your form wasn't passing existing link IDs, so updateOrCreate couldn't match records correctly. Modify your Blade view to add a hidden input for each existing link's ID:

@extends('Admin.master')
@section('content')
<div class="p-5">
 <h3><i class="fas fa-link ml-2"></i>لینک ها</h3><hr>
 <form action="{{ route('links.store') }}" method="post" id="linkForm">
 @csrf
 <div id="showDynamic">
     <!-- Render existing links with their IDs -->
     @foreach ($links as $index => $link)
     <div class="row mb-2">
         <div class="col-sm-12 col-md-3 mb-2 mb-md-0">
             <input class="form-control" placeholder="عنوان" name="links[{{ $index }}][title]" value="{{ $link->title }}">
         </div>
         <div class="col-sm-12 col-md-3 mb-2 mb-md-0">
             <input class="form-control" placeholder="لینک" name="links[{{ $index }}][link]" value="{{ $link->link }}">
         </div>
         <div class="col-sm-12 col-md-2">
             <input type="hidden" name="links[{{ $index }}][id]" value="{{ $link->id }}">
             <a class="btn btn-primary add m-1">افزودن</a>
             <a class="btn btn-danger delete m-1">حذف</a>
         </div>
     </div>
     @endforeach
 </div>
 <button type="submit" class="btn btn-success mt-3">ذخیره</button>
 </form>
</div>
@endsection

C. Fix Client-Side Dynamic Field Logic

Your script had mixed server/client count handling leading to incorrect input naming. Update the script to start counting from the number of existing links:

@section('script')
<script>
$(document).ready(function(){
    // Start count from the number of existing links
    let count = {{ $links->count() }};

    // Add new dynamic field
    $(document).on('click' , '.add' , function(){
        addDynamic(count);
        count++;
    });

    // Delete field
    $(document).on('click', '.delete', function() {
        $(this).closest('.row').remove();
    });

    function addDynamic(number) {
        let html = `
        <div class="row mb-2">
            <div class="col-sm-12 col-md-3 mb-2 mb-md-0">
                <input class="form-control" placeholder="عنوان" name="links[${number}][title]">
            </div>
            <div class="col-sm-12 col-md-3 mb-2 mb-md-0">
                <input class="form-control" placeholder="لینک" name="links[${number}][link]">
            </div>
            <div class="col-sm-12 col-md-2">
                <a class="btn btn-primary add m-1">افزودن</a>
                <a class="btn btn-danger delete m-1">حذف</a>
            </div>
        </div>
        `;
        $('#showDynamic').append(html);
    }
});
</script>
@endsection

2. Fixing Responsive Button Issues

The fixes above already address responsive behavior by:

  • Using col-sm-12 col-md-3 for input fields (full width on small screens, 3 columns on medium+)
  • Using col-sm-12 col-md-2 for buttons (full width on small screens, 2 columns on medium+)
  • Adding mb-2 mb-md-0 to create spacing between inputs and buttons on small screens
  • Adding m-1 to buttons for consistent spacing across all screen sizes

Optional: Add Ajax Form Submission (If Needed)

If you want to submit the form without a page reload, add this script to handle Ajax submission:

<script>
$(document).on('submit', '#linkForm', function(e){
    e.preventDefault();
    let formData = $(this).serialize();
    
    $.ajax({
        url: $(this).attr('action'),
        method: 'POST',
        data: formData,
        success: function(response){
            alert('لینک ها با موفقیت ذخیره شدند');
            location.reload(); // Refresh to show updated links
        },
        error: function(xhr){
            let errors = xhr.responseJSON.errors;
            let errorMessage = '';
            $.each(errors, function(key, value){
                errorMessage += value[0] + '\n';
            });
            alert(errorMessage);
        }
    });
});
</script>

These changes should resolve both your data saving/update issues and the responsive button problems. Let me know if you run into any further issues!

内容的提问来源于stack exchange,提问作者user14565701

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:57:38