Laravel 5.6中Eloquent的update方法失效,请求协助排查
Hey there, let's dig into why your update feature isn't working as expected! Based on the code snippets you shared, here are the most common issues to check and fix:
1. Missing Mass Assignment Permissions (Super Common!)
Laravel protects models from mass assignment by default, so if your ItemName model doesn't explicitly list the fields you're trying to update, the update($request->all()) call will silently ignore them.
Add the $fillable property to your ItemName model:
// app/Models/ItemName.php class ItemName extends Model { protected $fillable = [ 'inc', 'item_name', 'short_name', 'definition_eng', 'definition_ind' ]; }
2. Verify Route Model Binding Setup
You're using implicit route model binding (ItemName $itemName), which should work, but double-check:
- The route parameter name matches your controller variable: Resource routes use
{itemName}(lowercase camelCase), which aligns with$itemName—that's good. - Your model uses the default primary key (
id). If you've changed it to something else (likeitem_id), addprotected $primaryKey = 'item_id';to your model. - Make sure you've imported the model correctly at the top of your controller:
use App\Models\ItemName;
3. Check Form Request Method
HTML forms only support GET and POST methods, but Laravel requires a PUT or PATCH request for updates. Ensure your form includes the method spoofing field:
<form action="{{ route('ItemName.update', $itemName) }}" method="POST"> @csrf @method('PUT') <!-- This is crucial! --> <!-- Your form fields here --> </form>
4. Validate Error Handling
If validation fails, Laravel will redirect back to the form, but you might not be seeing the error messages. Add error display in your view to debug:
@if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
You can also temporarily debug by dumping the request data in your controller to confirm it's being received:
public function update(Request $request, ItemName $itemName) { dd($request->all()); // Check if your form data is here // ... rest of your code }
5. Complete Your Return Response
Your code cuts off at return r...—make sure you're returning a valid response so the user knows the update worked. For a web app, a redirect with a success message is standard:
return redirect()->route('ItemName.index')->with('success', 'Item updated successfully!');
If none of these fix the issue, share more details like:
- Any error messages you're seeing (in the browser console or Laravel logs)
- Your form blade code
- The full
ItemNamemodel code
内容的提问来源于stack exchange,提问作者Dewa Aditya

