【问题标题】:Button for update function not working laravel 8 (CRUD)更新功能按钮不起作用 laravel 8(CRUD)
【发布时间】:2021-11-10 02:13:14
【问题描述】:

我是 laravel 8 的新手。当用户已经编辑他们的数据并将其存储在数据库中时,我尝试制作一个更新功能控制器。我尝试单击提交按钮,但当我尝试在 chrome 上进行检查时,它没有任何理由无法正常工作。所以我尝试了另一种方法,即注释 $request->validate 并且仅更改名称数据,而 organization_id 留空并返回 NULL。我想知道我们是否需要始终验证更新函数中的数据?

这是我的控制器

public function edit($id)
{
 $record = User::find($id);
 $org = Organisation::all();
 $t = Organisation::pluck("name");

 return view ('user.edit',compact('record','org','t'));
 }

public function edit_store(Request $request, $id)
{
  $request->validate([
  'name' => 'required',
  'organisation_id' => 'required',
  ]
  );

 $record= User::find($id);
 $record->name = $request->name;
 $record->organisation_id = $request->organisation_id;
 $record->save();

 return redirect ('user')->with('success', 'Thank you');
 }

这是我的编辑刀片

 <div class="card">
 <div class="card-body">
 <form action="{{route('user_edit_store1', $record->id)}}" method="POST">
  @csrf

 <input type="hidden" name="id" value="{{ $record->id }}">

 <div class="form-group row">
 <label for="name"
 class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
 <div class="col-md-6">
 <input id="name" type="text"
 class="form-control @error('name') is-invalid @enderror" name="name"
 value="{{ old('name') ? old('name') : $record->name }}" 
 </div>
 </div>

<div class="form-group row">
<label for="organisation_id"
 class="col-md-4 col-form-label text-md-right">{{ __('Organisation') }}</label>
 <div class="col-md-6">
 {!! Form::open(['route' => 'user_store']) !!}
 {!! Form::select('id', $t, 'id',  ['class' => 'form-control']) !!}
 </div>
 </div>

 <div class="form-group row mb-0">
<div class="col-md-6 offset-md-4"> 
<button type="submit" class="btn btn-primary" >
  {{ __('Save') }} 
 </button>
</div>
</div>
</form>
</div>
</div>

路线

Route::get('user_edit/{id}',[UserController::class,'edit'])->name('user_edit');
Route::post('user_edit_store/{user}',[UserController::class,'edit_store'])->name('user_edit_store1');

模型 user.php

protected $fillable = [
'name',
'organisation_id',
];

【问题讨论】:

  • 您显示的代码中有几个问题。 1)您有 2 个嵌套的 &lt;form&gt;s,(尽管其中只有一个是关闭的)。那是无效的,将不起作用。 2)第一个表单动作(route('user_edit_store1', $record-&gt;id))使用the wrong syntax for specifying a route parameter。 3) Form::select('id'... 创建一个名为 id&lt;select&gt;,但您的验证和控制器方法正在寻找一个名为 organisation_id 的字段。
  • 4) 您的编辑视图没有show validation errors

标签: laravel-8 php-7.4


【解决方案1】:

您使用Form::select 表单助手创建的&lt;select&gt; 的名称似乎是“id”而不是“organisation_id”,这将导致验证失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多