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

浪子不回头ぞ 提交于 2019-12-11 03:26:41

问题


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 $image I get:

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.


回答1:


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




回答2:


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().

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

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



来源:https://stackoverflow.com/questions/23994179/error-call-to-undefined-method-stdclassdelete-while-trying-delete-a-row-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!