view側でinput type=”checkbox” class=”checkBoxes” name=”checkBoxArray[]” value=”{{$photo->id}}” と書いて、配列でcontrollerに送り、Photo::findOrFail($request->checkBoxArray)で受け取る。
Route
Route::delete('/delete/media', 'AdminMediasController@deleteMedia');
@if($photos) <form action="/delete/media" method="post" class="form-inline"> {{csrf-field()}} {{method_field('delete')}} <div class="form-group"> <select name="checkBoxArray" id="" class="form-control"> <option value="delete">Delete</option> </select> </div> <div class="form-group"> <input type="submit" class="btn btn-primary"> </div> <table class="table table-striped"> <thead> <tr> <th><input type="checkbox" id="options"></th> <th>Id</th> <th>Name</th> <th>Created date</th> </tr> </thead> <tbody> @foreach($photos as $photo) <tr> <th><input type="checkbox" class="checkBoxes" name="checkBoxArray[]" value="{{$photo->id}}"></th> <td>{{$photo->id}}</td> <td><img height="50" src="/{{$photo->file}}"></td> <td>{{$photo->created_at ? $photo->created_at : 'no date'}}</td> <td> {!! Form::open(['method'=>'DELETE', 'action'=>['AdminMediasController@destroy', $photo->id]]) !!} {{ csrf_field()}} <div class="form-group"> {!! Form::submit('Delete', ['class'=>'btn btn-danger']) !!} </div> {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </form> @endif
public function deleteMedia(Request $request){ if(isset($request->delete_single)){ $this->destroy($request->photo); return redirect()->back(); } if(isset($request->delete_all) && !empty($request->checkBoxArray)){ $photos = Photo::findOrFail($request->checkBoxArray); foreach($photos as $photo){ $photo->delete(); } return redirect()->back(); } else { return redirect()->back(); } }
$(document).ready(function(){ $('#options').click(function(){ if(this.checked){ $('.checkBoxes').each(function(){ this.checked = true; }); } else { $('.checkBoxes').each(function(){ this.checked = false; }); } }); });
一括削除はUX上、あまり宜しくないと思ったが、よく考えたら複数一括処理はselectで一括ステータス変更などにも使えるので、書き方自体は覚えておきたい。