我试图通过 routes.php 删除一个文件,但它产生了以下错误:
FatalErrorException in routes.php line 113: Call to a member function delete() on null
这是在删除按钮中放置函数的 View 。
<div class="col-md-12 col-xs-12">
<div class="row">
@foreach($properties->files as $index=>$file)
<div class="col-sm-6 col-md-2">
<div class="thumbnail">
<img src="{{ URL::asset('uploads/products/' . $file->name) }}" alt="{{ $file->property_id }}" width="300" height="200">
<div class="caption">
<div class="caption" align="center">
<form action="{{ url('file/'.$file->id) }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button onclick="return confirm('Está seguro eliminar esta imagen?')" class="button btn btn-danger btn-xs" data-toggle="tooltip" data-placement="top" title="Eliminar imagen"><i class="material-icons delete-white">delete</i></button>
</form>
</div>
</div>
</div>
</div>
@endforeach
</div>
</div>
这是我用来删除目录和数据库中文件的路径。
// Delete files
Route::delete('/file/{id}', function ($id) {
//File::findOrFail($id)->delete();
$file = File::find(Input::get('id')->delete());
$filename= Input::get('upload');
$path = 'uploads/products/' . $file->filename;
//return redirect('/');
return redirect()->back()->with('success', 'Imagen eliminada satisfactoriamente!!!');
});
最佳答案
处理请求输入时,有两类参数:路由参数和查询参数。路由参数是 url 的一部分,并作为参数提供给路由处理程序(闭包或 Controller 方法),而查询参数来自查询字符串,并通过请求数据(您正在使用的输入外观)提供。
如所写,您的代码有两个问题。首先,您的文件 ID 是一个路由参数,但您正试图像访问查询参数一样访问它。其次,您实际上是在尝试对 id 本身调用 delete()
,它实际上是 null
,因为它不作为查询参数存在。
您注释掉的行应该可以正常工作:
File::findOrFail($id)->delete();
当您删除 File
记录时,您似乎也在尝试从文件系统中删除文件。我建议您将 deleted()
事件添加到您的 File
方法中,以便每当删除 File
模型时,它都会删除关联的文件来自文件系统。
class File extends Model
{
public static function boot()
{
// make sure to call the parent boot
parent::boot();
// this function will be called whenever a File is deleted
static::deleted(function ($model) {
// delete the file when the model is deleted. very basic,
// you'll want to add in more sanity checks, etc.
// get the file path
$path = 'uploads/products/' . $model->filename;
// delete the file
unlink($path);
});
}
}
您还可以使用 deleting()
事件,该事件将在文件记录从数据库中删除之前触发。如果这样做,如果文件删除失败,您可以从事件中返回 false
,这将防止记录从数据库中删除。
关于php - routes.php 中的 FatalErrorException 第 113 行 : Call to a member function delete() on null in Laravel 5. 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42708716/