i have table link delete
@foreach ($tasks $task) <tr> <td>{{$task->id}}</td> <td>{{$task->name}}</td> <td><a href="javascript:void(0)" onclick="eliminar({{$task->id}})" id="borrar_{{$task->id}}" name="borrar_{{$task->id}}" class="btn btn-danger">eliminar</a></td> </tr> @endforeach
and javascript code,which made petition destroy method of controller
function eliminar(id){ var _token = $('meta[name="_token"]').attr('content'); $.ajax({ type: "delete", url: "task/"+id, data: { _token : _token}, success: function (data) { $("#borrar_"+id).closest('tr').fadeout(); }, error: function (data) { alert('no se pudo eliminar el resgistro'); } }); }
the controller
<?php namespace app\http\controllers; use illuminate\http\request; use app\http\requests; use app\task; class taskcontroller extends controller { . . . /** * remove specified resource storage. * * @param int $id * @return \illuminate\http\response */ public function destroy($id) { task::destroy($id); } }
when button clicked parent table row fades out ,but think it's not best way it. how can check if task::destroy($id)
made succesfully or not send succes o error response ajax request
in controller:
public function destroy($id) { $deleted = task::destroy($id); return $deleted ? 'deleted' : 'error'; }
in js:
success: function (data) { if(data === 'deleted'){ $("#borrar_"+id).closest('tr').fadeout(); }else{ alert('no se pudo eliminar el resgistro'); } },
another method find useful use of findorfail model, returns 404 if model not found , ajax go error response, if model found delete method should return true, so:
public function destroy($id) { $task = task::findorfail($id); return $task->delete(); // return true }