简体   繁体   English

route.php第113行中的FatalErrorException:在Laravel 5.2中,在null上调用成员函数delete()

[英]FatalErrorException in routes.php line 113: Call to a member function delete() on null in Laravel 5.2

I am trying to delete a file through routes.php but it is generating the following error: 我正在尝试通过routes.php删除文件,但它会产生以下错误:

FatalErrorException in routes.php line 113: Call to a member function delete() on null

This is the view where the function is placed in the delete button. 该功能位于删除按钮中的视图。

<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>

And this is the path I'm using to delete the file in the directory and database. 这是我用来删除目录和数据库中文件的路径。

// 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!!!');

    });

When processing request input, there are two types of parameters: route parameters and query parameters. 处理请求输入时,有两种类型的参数:路由参数和查询参数。 Route parameters are part of the url and are made available as parameters to the route handler (closure or controller method), whereas query parameters come from the query string and are made available through the request data (Input facade that you are using). 路由参数是url的一部分,可作为参数提供给路由处理程序(闭​​包或控制器方法),而查询参数则来自查询字符串,并可以通过请求数据(您正在使用的Input Facade)使用。

As written, your code has two issues. 如所写,您的代码有两个问题。 First, your file id is a route parameter, but you're trying to access it as if it were a query parameter. 首先,您的文件ID是一个路由参数,但是您试图像访问查询参数一样对其进行访问。 Second, you're actually attempting to call delete() on the id itself, which is actually null since it doesn't exist as a query parameter. 其次,您实际上是在尝试对id本身调用delete() ,因为它不作为查询参数存在,所以实际上为null

The line that you have commented out should work fine: 您注释掉的行应该可以正常工作:

File::findOrFail($id)->delete();

It looks like you're also attempting to delete a file from the file system when you delete your File record. 看起来当您删除File记录时,您也在尝试从文件系统中删除File I would suggest you add a deleted() event to your File method, so that whenever a File model is deleted, it deletes the associated file from the file system. 我建议您向File方法中添加一个deleted()事件,以便每当删除一个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);
        });
    }
}

You could also use the deleting() event, which will fire before the File record is deleted from the database. 您还可以使用delete deleting()事件,该事件将在从数据库中删除文件记录之前触发。 If you did this, you could return false from the event if the file fails to delete, and that will prevent the record from being deleted from the database. 如果这样做,则如果文件删除失败,则可以从事件中返回false ,这将防止从数据库中删除记录。

The error is generated because you are trying to retrieve a value from an input field which does not exist. 生成该错误是因为您试图从不存在的输入字段中检索值。 You should read the documentation and see the difference between Input and Request Requests & Input 您应该阅读文档并查看“输入”与“请求请求”和“输入”之间的区别

Since there is no input field in your form and you are just passing and id in your form request, change this 由于您的表单中没有输入字段,而您只是在表单请求中传递ID和ID,因此请更改此设置

 $file = File::find(Input::get('id'))->delete();

to this 对此

 $file = File::find(Request::segment(2))->delete();

It should work fine now. 现在应该可以正常工作了。

Updated: Make sure you have your model class in your web route. 已更新:确保您的模型路线中包含模型类。 Also make sure you're using Request use Illuminate\\Http\\Request; 还要确保您正在使用Request use Illuminate\\Http\\Request; In your web route use Request. 在您的网络路由中,使用请求。 Do the following: Change this 请执行以下操作:更改此

// 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!!!');

});

to this 对此

// Delete files
Route::delete('/file/{id}', use function (Request $request) {

    File::findOrFail($request->segment(2))->delete();

    $filename= Input::get('upload');
    $path = 'uploads/products/' . $file->filename;

    //return redirect('/');
    return redirect()->back()->with('success', 'Imagen eliminada satisfactoriamente!!!');

});

Thanks for the recommendations, but I decided to change the method to handle these events. 感谢您的建议,但我决定更改处理这些事件的方法。

1 - I create a new controller (FilesController) and through the controller I passed the parameters for elimination in the BD and the public path, for this controller we use the destroy method. 1-我创建了一个新的控制器(FilesController),并通过该控制器在BD和公共路径中传递了要消除的参数,对于该控制器,我们使用destroy方法。

2 - I create a Route resource from the same controller. 2-我从同一控制器创建Route资源。

This is the File model: 这是文件模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class File extends Model
{
    protected $table = 'files';

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

    // Relation with Property
    public function property()
    {
        return $this->belongsTo('App\Property');
    }
}

This is the FilesController method: 这是FilesController方法:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\File;
use Redirect;
use Storage;

class FilesController extends Controller
{
    public function destroy(Request $request, $id)
    {

        $file = File::find($id);

        $fileName = $file->name;

        //dd($fileName);

        $file_path = public_path() . "/uploads/products/" . $fileName;

        //dd($file_path);

        if(File::exists($file_path))
        { 
            unlink($file_path);
        }

        $file->delete();

        return redirect()->back()->with('success', 'Imagen eliminada satisfactoriamente!!!');

    }
}

The route: 路线:

Route::resource('properties','PropertyController');

And this is the part in the view that delete the files: 这是视图中删除文件的部分:

<div class="col-md-12 col-xs-12">
        <div class="row">
            @foreach($properties->files as $index=>$file)

                  <div class="col-sm-4 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::open(['method' => 'DELETE','route' => ['files.destroy', $file->id],'style'=>'display:inline']) !!}

                                {!! Form::hidden('_method', 'DELETE') !!}

                                {!! csrf_field() !!}

                                @permission('role-delete')
                                <button onclick="return confirm('Se eliminara la propiedad de la lista')" class="button btn btn-danger btn-xs" data-toggle="tooltip" data-placement="top" title="Eliminar imagen" data-id="{{$file->id}}"><i class="material-icons delete-white">delete</i></button>
                                @endpermission

                            {!! Form::close() !!}
                        </div>
                      </div>
                    </div>
                  </div>           

            @endforeach
        </div>
    </div>

With this simple form we can remove an image of the DB and the public path. 通过这种简单的形式,我们可以删除数据库和公共路径的图像。

I hope to collaborate with other passionate people. 我希望与其他热情的人合作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel注册错误:AuthenticatesAndRegistersUsers.php中的FatalErrorException第41行:在null上调用成员函数validator() - Laravel Registration Error: FatalErrorException in AuthenticatesAndRegistersUsers.php line 41: Call to a member function validator() on null 在route.php第51行中出现FatalErrorException:找不到类“ app \\ Game”,laravel 5.1 - FatalErrorException in routes.php line 51: Class 'app\Game' not found laravel 5.1 routes.php第22行中的FatalErrorException:未找到类“绘画” - FatalErrorException in routes.php line 22: Class 'Painting' not found RedirectResponse.php 75行中的Lumen FatalErrorException:在null上调用成员函数flashInput() - Lumen FatalErrorException in RedirectResponse.php line 75: Call to a member function flashInput() on null 如何在Laravel中从route.php调用静态函数 - How to call static function from routes.php in Laravel 从 Laravel Routes.php 调用控制器函数 - Call Controller Function from Laravel Routes.php 在null Laravel 5.2上调用成员函数 - call to a member function on null Laravel 5.2 FatalErrorException 在 null 上调用成员 function except() - FatalErrorException Call to a member function except() on null 从Laravel 5.2中的route.php获取所有控制器和资源 - Get all the Controller & resources from the routes.php in Laravel 5.2 route.php中的Laravel 5.2 Web中间件组不见了 - Laravel 5.2 web middleware group in routes.php is gone
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM