我正在发出表单删除请求,每次尝试删除某些内容时,都会收到错误消息“调用成员函数 delete on null”。我很长一段时间没有使用 Laravel,我已经忘记了它是如何工作的,现在我从头开始学习,遵循 Laracast 的教程。我比较了代码,一切都很好,但我总是遇到一些错误,而且我找不到问题......
网页.php
Route::resource('projects', 'ProjectsController');
ProjectsConroller
public function destroy($id)
{
$project = Project::find($id);
$project->delete();
return redirect('/projects');
}
编辑刀片.php
@extends('layout')
@section('content')
<h1>Edit Project</h1>
<form method="POST" action="{{ url('/projects/$project->id') }}" >
{{ method_field('PATCH') }}
{{ csrf_field() }}
<div class="field">
<label class="label" for="title">Title</label>
<div class="control">
<input type="text" class="input" name="title" placeholder="Title" value="{{ $project->title }}">
</div>
</div>
<div class="field">
<label class="label" for="description">Description</label>
<div class="control">
<textarea name="description" class="textarea">{{ $project->description }}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Update Project</button>
</div>
</div>
</form>
<form method="POST" action="{{ url('/projects/$project->id') }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<div class="field">
<div class="control">
<button type="submit" class="button">Delete Project</button>
</div>
</div>
</form>
@endsection()
这部分代码是错误的: <form method="POST" action="{{ url('/projects/$project->id') }}"
它传递 $project->id 作为 ID 而不是评估。你有两种方式:
<form method="POST" action="{{ url('/projects/'.$project->id) }}"
<form method="POST" action="{{ url("/projects/$project->id") }}"
另外,在您的控制器方法中,您可能希望使用findOrFail()
而不是find()
这样,当找不到模型时,它会返回 404。如果找不到模型,find() 将返回 null,并且您已经尝试调用->delete()
null。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句