【问题标题】:Laravel resource route is not updating in database using {{method_field('PATCH')}}Laravel 资源路由未使用 {{method_field('PATCH')}} 在数据库中更新
【发布时间】:2020-05-15 17:52:37
【问题描述】:

Laravel resource 当我点击更新按钮时,路由没有更新,但它在同一进程中存储。

我正在使用data-toggle="modal" 更新我的值,但它没有更新我的类别?

我的问题到底在哪里?我检查我的 id 是否正确传递,但它不会用于我的更新控制器功能。我在控制器的更新功能中使用dd($request->all()); 进行检查。

我的路线是

Route::resource('/mother-category', 'MotherCategoryController');

我的更新和存储功能是

public function store(Request $request)
    {
        $validator =Validator::make($request->all(), [
            'mother_name' => 'required',

        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }

        MotherCategory::insert([
            'mother_name'=>$request->mother_name
        ]);

        return redirect()->back()->with('message','Mother Category Created Successfully');
    }



    public function update(Request $request, MotherCategory $motherCategory)
    {

        $motherCategory->update([
            'mother_name' => $request->mother_name
        ]);

        return redirect()->back()->with('message','Mother Category Updated successfully');
    }

我的刀片文件是


@extends('layouts.master')

@section('title', 'Add Mother Category')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-lg-10 mx-auto">
                <form action="{{route('mother-category.store')}}" method="post">
                    @csrf
                    <div class="card">
                        <div class="card-header">
                            <h4 style="text-align: center">Add a mother category</h4>
                        </div>
                        <div class="card-body">
                            <div class="form-row mb-3">
                                <div class="col">
                                    <small class="text-uppercase text-dark">Mother Category<span
                                            class="required text-danger">*</span></small>
                                    <input type="text" id="mother_name" name="mother_name" class="form-control"
                                           placeholder="Mother Category" required>

                                    @if ($errors->has('mother_name'))
                                        <small
                                            class="form-control-feedback text-danger">{{ $errors->first('mother_name') }}</small>
                                    @endif
                                </div>
                            </div>
                            <div class="form-row mb-3">
                                <div class="col">
                                    <button type="submit" class="btn btn-success"><i class="fa fa-check"></i> Add
                                    </button>
                                    <button type="button" class="btn btn-inverse">Cancel</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <br>

        <div class="row">
            <div class="col-md-12">
                <div class="card comp-card">
                    <div class="card-body">
                        <h5 class="w-100 text-center">All Mother categories</h5>
                        <div class="table-responsive">
                            <table class="table table-hover" id="motherTable">
                                <thead>
                                <tr>
                                    <th scope="col">#</th>
                                    <th scope="col">Name</th>
                                    <th scope="col">Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                @foreach(App\Models\MotherCategory::all() as $index => $mc)
                                    <tr>
                                        <th scope="row">{{$index+1}}</th>
                                        <td>{{$mc->mother_name}}</td>
                                        <td>
                                            <a href="#" class="btn btn-sm btn-info" data-toggle="modal"
                                               data-target="#exampleModalCenter{{$mc->id}}">Edit</a>
                                            <a id="deleteBtn" data-id="{{$mc->id}}" href="#"
                                               class="btn btn-sm btn-danger">Delete</a>
                                        </td>
                                    </tr>
                                    <div class="modal fade" id="exampleModalCenter{{$mc->id}}" tabindex="-1" role="dialog"
                                         aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                                        <div class="modal-dialog modal-dialog-centered" role="document">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalCenterTitle">Update</h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                    <form action="{{route('mother-category.update',$mc->id)}}"
                                                          method="post">
                                                        {{ csrf_field() }}
                                                        {{method_field('PATCH')}}
                                                        <div class="form-group">
                                                            <label for="exampleInputEmail1">Name</label>
                                                            {{-- <input type="hidden" name="id" value="{{$mc}}"> --}}
                                                            <input name="mother_name" type="text" class="form-control"
                                                                   id="exampleInputEmail1" aria-describedby="emailHelp"
                                                                   placeholder="Enter mother category"
                                                                   value="{{$mc->mother_name}}"><br><br>
                                                            <input type="submit" class=" btn btn-success"
                                                                   value="Update">
                                                        </div>
                                                    </form>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary"
                                                            data-dismiss="modal">Close
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection



@section('script')

    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.5/js/bootstrap-select.min.js"></script>

    <script>
        $('#motherTable').DataTable({

        });
    </script>

    <script>
        $(document).on('click', '#deleteBtn', function (el) {
            var mcId = $(this).data("id");
            swal({
                title: "Are you sure?",
                text: "Once deleted, you will not be able to recover this category!",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            })
                .then((willDelete) => {
                    if (willDelete) {
                        swal("You have deleted a mother category!", {
                            icon: "success",
                        });
                        window.location.href = window.location.href = "mother-category/delete/" + mcId;
                    }


                });
        });

        $(document).on('click', '#deleteNo', function (el) {
            swal("Oops", "You can't delete this. Some item belongs to it!!", "error")
        })
    </script>
@endsection

渲染的html


<div role="document" class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
        <div class="modal-header"><h5 id="exampleModalCenterTitle" class="modal-title">Update</h5>
            <button type="button" data-dismiss="modal" aria-label="Close" class="close"><span
                    aria-hidden="true">×</span></button>
        </div>
        <div class="modal-body">
            <form action="http://localhost:8000/mother-category/2" method="POST"></form>
            <input type="hidden" name="_token" value="F0fzi1ufy2sO9r8apQ6NTrDtDgfGqycpEiUvaMEG"> <input type="hidden"
                                                                                                        name="_method"
                                                                                                        value="PUT">
            <div class="form-group"><label for="exampleInputEmail1">Name</label> <input name="mother_name" type="text"
                                                                                        id="exampleInputEmail1"
                                                                                        aria-describedby="emailHelp"
                                                                                        placeholder="Enter mother category"
                                                                                        value="Plaster &amp; gypsum board."
                                                                                        class="form-control fill user-success"><br><br>
                <input type="submit" value="Update" class=" btn btn-success"></div>
        </div>
        <div class="modal-footer">
            <button type="button" data-dismiss="modal" class="btn btn-secondary">Close
            </button>
        </div>
    </div>
</div>

【问题讨论】:

  • 如果它没有达到你的更新方法,那么还会发生什么? 404?
  • 当我点击更新按钮时没有任何反应。
  • 你能检查你的页面并显示呈现的 HTML 吗?那么您的表单似乎有问题。
  • 是的,我检查并渲染了 HTML。
  • 但是您能否将呈现的 html 添加到您的问题中 - 可能您的表单定义存在问题。

标签: php laravel laravel-5 routes


【解决方案1】:

刀片文件

    <form method="POST" action="{{ route('admin.category.update',$category->id) }}">
          @csrf
           @method('PUT')
            <div class="form-group form-float">
             <div class="form-line">
              <input value="{{ old('name') }}{{ $category->name }}" name="name" type="text" class="form-control">
               <label class="form-label">{{ __('Name') }}</label>
                </div>
                 </div>
                    <br>                      
               <a href="{{ route('admin.category.index') }}"  class="btn btn-danger m-t-15 waves-effect">{{ __('BACK') }}</a>
             <button type="submit" class="btn btn-primary m-t-15 waves-effect">{{ __('SUBMIT') }}</button>
         </form>

web.php

    Route::resource('category','CategoryController');

    });

控制器


     public function edit($id)
        {
            $category =Category::find($id);
            return view('admin.category.edit',compact('category'));
        }

     public function update(Request $request, $id)
        {
            $this->validate($request,[
                'name' => 'required|unique:categories'
            ]);
            $category = Category::find($id);
            $category->name = $request->name;
            $category->slug = str_slug($request->name);
            $category->save();
            Toastr::success('Category Successfully Updated','Success');
            return redirect()->route('admin.category.index');

        }

【讨论】:

  • 可能你不明白我的问题。我没有任何编辑视图,它是data-toggle="modal"。我只使用数据切换,它不应该打开另一个页面。
【解决方案2】:

正如评论所述,问题是表单正在直接关闭,因为它可以在 html 中看到

<div class="modal-body">
  <form action="http://localhost:8000/mother-category/2" method="POST"></form>
    <input type="hidden" name="_token" value="F0fzi1ufy2sO9r8apQ6NTrDtDgfGqycpEiUvaMEG">
    <input type="hidden" name="_method" value="PUT">
    ...

由于刀片不直接关闭(见下文)

<form action="{{route('mother-category.update',$mc->id)}}" method="post">
  {{ csrf_field() }}
  ...

问题一定是你的html本身

快速谷歌将我发送到此:Laravel blade form closing issue

问题是您在表格中使用表格。您必须将其包装在 td 中或将其完全移出您的桌子。

希望这能解决问题

【讨论】:

    【解决方案3】:

    {{method_field('PATCH')}} 替换为{{method_field('PUT')}}

    或者你可以使用刀片指令@method('PUT')

    <form action="/foo/bar" method="POST">
        @method('PUT')
    
        ...
    </form>
    

    【讨论】:

    • 仍然无法正常工作,我认为主要问题是它不会更新功能。
    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 2019-02-20
    • 2021-05-24
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2015-08-11
    • 2013-08-08
    相关资源
    最近更新 更多