Delete multiple rows from database based on the checkboxes

3k Views Asked by At

I have a problem with a delete from database. If for example I checked 5 items only one is deleted. Normaly the script is correctly: My view:

{{ Form::open(array('url'=>'/administration/photo/deletePhoto','method' => 'post','files'=>true)) }}
            @foreach($aPhotoInCategory as $photo)
                {{ HTML::image($photo->name,'alt', array('class'=>'news-content-image','width' => 95, 'height' => 70 )) }}
                {{ Form::checkbox('aObjects[]',$photo->id)}}
                {{ Form::hidden('id',$aOnePhotoCategory['id']) }}
            @endforeach
        <br/><br/>
{{ Form::submit('Delete',array('class'=>'btn btn-primary')) }}
{{ Form::close() }}

My controller:

public function deletePhoto(){
    $aPhotoChecked = Input::get('aObjects');
    $id            = Input::get('id');
    foreach($aPhotoChecked as $photo){
        $oPhoto = \Photo::find($photo);
        if($oPhoto){
            File::delete('public/'.$oPhoto->name);
            $oPhoto->delete();
            return Redirect::to('administration/category_photo/edit/'.$id)
                   ->with('message_succes','Succes');
        }
    }
}

The array $aPhotoChecked contains all items checked, but when I press on the delete button only one item is deleted not all checked. Help me please.

2

There are 2 best solutions below

0
Eimantas Gabrielius On

have you tried :

$aPhotoChecked = Input::get('aObjects');

foreach($aPhotoChecked as $key => $n ) 
{
    $oPhoto = \Photo::find( $aPhotoChecked[$key] );
    .....
    // you can dump here and debug your arrays :)
}   
0
Harea Costea On

I resolve the problem with a for :

for($i=0;$i<count($aPhotoChecked);$i++){
        $oPhoto = \Photo::find($aPhotoChecked[$i]);
        Log::info(print_r(public_path(),true));
        File::delete(public_path().'/'.$oPhoto->name);
        DB::table('photo')->where('id', '=', $aPhotoChecked[$i])->delete();
    }