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

问题描述:

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.

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

  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(); 
返回Redirect :: back()
  - > with('  form_success',1)
  - > with('form_message','Image successfully deleted!'); 
} 
  code>  pre> 
 
 

如果我尝试返回值 $ image code>我得到: p>

  stdClass Object([id] => 49 [site_id] => 1 [page_id] =>  [location] =>图库[alt] => [路径] => 60e52a2755ffe8923d5ac1232f5d9154.jpg)
  code>  pre> 
 
 

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

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

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.