view和jq
@extends('layouts.main') @section('content') <h3>User List</h3> <p class="text-center text-info"></p> <table class="table table-striped"> <tr> <th>#</th> <th>name</th> <th>Email</th> <th>option</th> </tr> @foreach($users as $u) <tr data-id='{{ $u->id }}'> <td>{{ $u->id }}</td> <td>{{ $u->name }}</td> <td>{{ $u->email }}</td> <td> <a class='btn-edit' href="#">edit</a> <a class='btn-delete' href="#!">delete</a> </td> </tr> @endforeach </table> {!! $users->render() !!} <form method="POST" action='/user/:USER_ID' id='form-delete'> <input type="hidden" name='_method' value='DELETE'> {{ csrf_field() }} </form> @stop @section('script') <script type="text/javascript"> $(function(){ $('.btn-delete').click(function(e){ e.preventDefault(); var row = $(this).parents('tr'); var id = row.data('id'); var form = $('#form-delete'); var url = form.attr('action').replace(':USER_ID', id); var data = form.serialize(); row.fadeOut(); $.post(url, data, function(result){ $('.text-info').text(result.name + ' ' + result.message ); }).fail(function () { $('.text-info').text('delete failed .'); row.fadeIn(); }); }); }); </script> @stop
controller
public function destroy($id, Request $request) { $user = User::findOrFail($id); $name = $user->name; $user->delete(); $message = 'deleted successfuly.'; if ($request->ajax()) { return response()->json([ 'name' => $name, 'message' => $message ]); } }
route
Route::resource('user', 'UserController');