Laravel 4 (Eloquent) Error deleting records

0

Hello, in this code below I make a delete in the database of the selected records in a list of chekboxes.

I have an array of Ids that is mounted as follows:

Array (
    [0] => 810
    [1] => 811
)

On top of this array I make a foreach search each record and call the delete method, complete code below:

public function destroy_download($id = 0){
    $ids = ($id >= 1) ? array($id) : Input::get('ids');

    if( ! empty($ids) ){
        foreach ($ids as $id) {
            $download = Download::find($id);
            $download->delete();
        }
    }
}

This should work correctly, however it gives the following error:

Symfony \ Component \ Debug \ Exception \ FatalErrorException Call to a member function delete() on a non-object

on line:

$download->delete();

It's as if the record has not been found.

It removes the record in the database only that happens this error, can anyone imagine what it is?

The Array is correct, I've debugged but it always does.

    
asked by anonymous 09.04.2014 / 21:45

2 answers

1

Try the following:

public function destroy_download($id = 0){
    $ids = ($id >= 1) ? array($id) : Input::get('ids');

    if( ! empty($ids) ){
        foreach ($ids as $id) {
            try {
                Download::findOrFail($id)->delete();
            } catch (ModelNotFoundException $e){
                continue;
            }
        }
    }
}

This code will try to delete the id, if it does not find this record, go to the next one.

Hint : I think this is a good review, as we have unnecessary checks of the variable $ids

public function destroyDownloads(){
    $ids = Input::get('ids');

    // Não é um array? Aborta a função
    if(!is_array($ids)){
        return false;
    }

    foreach ($ids as $id){
        $this->deleteDownload($id);
    }

    // Ou returne um Response::make()
    return true;

}

private function deleteDownload($id){

    try {
        Download::findOrFail($id)->delete();
    } catch (ModelNotFoundException $e){
        // Caso queira verificar erros no futuro, basta verificar com um if
        // o retorno de $this->deleteDownload($id), se for falso o registro não existia
        return false;
    }

    return true;
}
    
10.04.2014 / 13:12
0

Confirm that the object ID exists by interpreting the result a bit, it seems the Download::find($id); function returns a string / null when the Id does not exist, therefore when you try to call the delete() method it generates this error.

Create a check that confirms that the ID actually exists before calling delete() .

    
09.04.2014 / 22:08