Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 447
lieroes Avatar asked Sep 15 '25 06:09

lieroes


2 Answers

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.

like image 139
user1669496 Avatar answered Sep 17 '25 20:09

user1669496


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

like image 27
BlackJack Avatar answered Sep 17 '25 19:09

BlackJack