尝试在 Laravel 中删除一行时出现错误“调用未定义的方法 stdClass::delete()”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23994179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:35:22  来源:igfitidea点击:

Error "Call to undefined method stdClass::delete()" while trying delete a row in Laravel

phplaravelmethods

提问by lieroes

My method to delete an image from database and local storage.

我从数据库和本地存储中删除图像的方法。

public function destroy($id) {
        $image = DB::table('images')->where('id', '=', $id)->first();
        //print_r($image);
        //return 'end';
        File::delete(public_path() . '/images/gallery/thumb-' . $image->path);
        File::delete(public_path() . '/images/gallery/' . $image->path);
        $image->delete();
        return Redirect::back()
                        ->with('form_success', 1)
                        ->with('form_message', 'Image successfully deleted!');
    }

If I try to return value of $imageI get:

如果我尝试返回$image我得到的值:

stdClass Object ( [id] => 49 [site_id] => 1 [page_id] => [location] => gallery [alt] => [path] => 60e52a2755ffe8923d5ac1232f5d9154.jpg ) 

So what's wrong with my code? Now my Laravel version is 4.2.1, but i try to downgrade him to 4.1.17, but no changes.

那么我的代码有什么问题?现在我的 Laravel 版本是 4.2.1,但我尝试将他降级到 4.1.17,但没有任何变化。

采纳答案by BlackHyman

Change your code according the following and I hope that your problem will be solved..

根据以下更改您的代码,我希望您的问题将得到解决..

public function destroy($id) {
        $query = DB::table('images')->where('id', '=', $id);
        $image = $query->first();
        //print_r($image);
        //return 'end';
        File::delete(public_path() . '/images/gallery/thumb-' . $image->path);
        File::delete(public_path() . '/images/gallery/' . $image->path);
        $query->delete();
        return Redirect::back()
                        ->with('form_success', 1)
                        ->with('form_message', 'Image successfully deleted!');
    }

first() and delete() these functions execute the code.So first assign your conditions to a variable and then execute them separately.Thanks

first() 和 delete() 这些函数执行代码。所以首先将你的条件分配给一个变量,然后分别执行它们。谢谢

回答by user1669496

The problem is once you call first(), the query is executed and the results are returned. You will have to call delete()before you call first().

问题是一旦您调用first(),就会执行查询并返回结果。你必须在打电话delete()之前先打电话first()

DB::table('images')->where('id', $id)->delete();

DB::table('images')->where('id', $id)->delete();

Since you are using the query builder, you are going to get back stdClassobjects (which do not have delete methods) as you've seen rather than the models you'd usually get when using Eloquent.

由于您使用的是查询构建器,因此您将返回stdClass您所看到的对象(没有删除方法),而不是使用 Eloquent 时通常会得到的模型。