我想知道如何在表单中放置一个csrf令牌,以便删除它?
这是我的代码:
路线:
Route::delete('category_delete/{id}',['as'=>'category_delete','uses'=>'CategoryController@destroy']);
index.blade.php
@section('adminContent')
{!! Form::token() !!}
<div class="table-responsive art-content">
<table class="table table-hover table-striped">
<thead>
<th> NAME</th>
<th> ACTIONS</th>
</thead>
<tbody>
@foreach($categoriesView as $category)
<tr>
<td>{!! $category->name!!}</td>
<td>{!! link_to_route('categories.edit', '', array($category->id),array('class' => 'fa fa-pencil fa-fw')) !!}</td>
<td><button type="button" id="delete-button" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="pagination"> {!! $categoriesView->render() !!}</div>
</div>
@stop
CategoryController:
public function destroy($id,Category $category)
{
$category = $category->find ( $id );
$category->delete ();
Session::flash ( 'message', 'The category was successfully deleted!.' );
Session::flash ( 'flash_type', 'alert-success' );
}
如果我使用ajax,javascript或jquery,代码应该如何?
答案 0 :(得分:0)
使用jquery我会做类似以下的事情。
在主视图的标题中添加以下行
<meta name="csrf-token" content="{{ csrf_token() }}" />
现在在你的javascript
function deleteMe(button)
{
// You might want to put the ajaxSetup function where it will always load globally.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if(confirm("Are you sure?"))
{
$.get(
'category_delete/'+button.id,
function( response )
{
// callback is called when the delete is done.
console.log('message = '+ response.message);
}
)
}
}
在index.blade.php中,让您的ID更具体
...
<td><button type="button" id=".$category->id" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o" onlick="deleteMe(this);></i></button>
...
在您的控制器中
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return response()->json(
'message' => 'Deleted',
)
}
Note
:无需添加
你认为Form::token
希望这会有所帮助.....
如果您只使用laravel进行此操作,我建议您使用link
而不是您正在使用的button
。
在index.blade.php中,让您的ID更具体
...
<td><a href="category_delete/".$category->id class="delete-button" data-url = "{!! url('category_delete')!!}"><i class="fa fa-trash-o"></i></td>
...
在您的控制器中
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return view('index');//important.
}
如果您希望链接看起来像按钮,请使用css
或css框架,例如bootstrap
那应该是它。希望这会有所帮助。