如何在 Laravel 5.7 中修复'call to a member functuin delete() on null'



我正在发出一个表单删除请求,每次我试图删除一些内容时,都会收到一个错误"调用成员函数delete on null"。我已经很久没有使用Laravel了,我已经忘记了它是如何工作的,现在我正在从头开始学习,遵循Laracast的教程。我比较了代码,一切都很好,但我总是会遇到一些错误,我找不到问题。。。

web.php

Route::resource('projects', 'ProjectsController');

项目收集器

public function destroy($id)
{
$project = Project::find($id);
$project->delete();
return redirect('/projects');
}

edit.blade.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,而不是评估。你有两种方法:

  1. <form method="POST" action="{{ url('/projects/'.$project->id) }}"
  2. <form method="POST" action="{{ url("/projects/$project->id") }}"

作为添加剂,在控制器方法中,您可能希望使用findOrFail()而不是find(),以便在找不到模型时返回404。如果找不到模型,find((将返回null,并且您已经在尝试对null调用->delete()

最新更新