I will destroy my user with a HTML link, but it doesn't seem to generate the correct link, what am i doing wrong?
我将用HTML链接销毁我的用户,但是它似乎没有生成正确的链接,我做错了什么?
public function destroy($id)
{
//Slet brugeren
$e = new User($id);
$e->destroy();
//Log også brugeren ud
Auth::logout();
//redrect til forsiden
Redirect::to("users/create");
}
In my view i call this {{URL::action('UserController@destroy', array($user->id))}}
在我的视图中,我调用这个{{URL: action('UserController@destroy', array($user->id))}
9 个解决方案
#1
33
Update 08/21/2017 for Laravel 5.x
Laravel 5.x于2017年8月21日更新
The question asks about Laravel 4, but I include this in case people looking for Laravel 5.x answers end up here. The Form and other helpers aren't available as of 5.x. You still need to specify a method on a form if you are doing something besides GET or POST. This is the current way to accomplish that:
这个问题问的是Laravel 4,但我把它包括在了寻找Laravel 5的人群中。x个答案在这里结束。表单和其他辅助程序无法使用5。x。如果您正在执行除GET或POST之外的操作,仍然需要在窗体上指定一个方法。这是目前实现这一目标的方法:
<form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<!-- other inputs... -->
</form>
You can also use {{ method_field('PUT') }}
instead of writing out the hidden _method
input.
您还可以使用{{method_field('PUT')},而不是写出隐藏的_method输入。
See https://laravel.com/docs/5.4/routing#form-method-spoofing
看到https://laravel.com/docs/5.4/routing form-method-spoofing
Original Answer for Laravel 4
Laravel 4的原始答案
I think when you click the link, it is probably sending a GET request to that end point. CRUD in Laravel works according to REST. This means it is expecting a DELETE request instead of GET.
我认为当你点击链接时,它可能会向那个端点发送一个GET请求。拉拉维尔的克鲁德按照休息工作。这意味着它期望的是删除请求而不是GET。
Here's one possibility from a tutorial by Boris Strahija.
这是鲍里斯·斯特拉希贾(Boris Strahija)的教程中的一种可能性。
{{ Form::open(array('route' => array('admin.pages.destroy', $page->id), 'method' => 'delete')) }}
<button type="submit" class="btn btn-danger btn-mini">Delete</button>
{{ Form::close() }}
This way, you send the request in a form with the DELETE method. The article explains why a traditional link won't work:
通过这种方式,您可以使用DELETE方法将请求发送到表单中。这篇文章解释了为什么传统的链接不起作用:
You may notice that the delete button is inside a form. The reason for this is that the destroy() method from our controller needs a DELETE request, and this can be done in this way. If the button was a simple link, the request would be sent via the GET method, and we wouldn’t call the destroy() method.
您可能注意到,delete按钮位于窗体内部。原因是来自我们的控制器的destroy()方法需要一个DELETE请求,可以这样做。如果按钮是一个简单的链接,那么请求将通过GET方法发送,我们不会调用destroy()方法。
#2
17
An cool ajax solution that works is this:
一个很酷的ajax解决方案是:
function deleteUser(id) {
if (confirm('Delete this user?')) {
$.ajax({
type: "DELETE",
url: 'users/' + id, //resource
success: function(affectedRows) {
//if something was deleted, we redirect the user to the users page, and automatically the user that he deleted will disappear
if (affectedRows > 0) window.location = 'users';
}
});
}
}
<a href="javascript:deleteUser('{{ $user->id }}');">Delete</a>
And in the UserController.php we have this method:
和用户控件。我们有这个方法:
public function destroy($id)
{
$affectedRows = User::where('id', '=', $id)->delete();
return $affectedRows;
}
#3
15
Another "clean" solution is to make it the Rails way as described here:
另一个“干净”的解决方案是使它成为这里描述的Rails方式:
-
Create a new .js file in public and write this function:
在公共场合创建一个新的.js文件并编写这个函数:
$(function(){ $('[data-method]').append(function(){ return "\n"+ "<form action='"+$(this).attr('href')+"' method='POST' style='display:none'>\n"+ " <input type='hidden' name='_method' value='"+$(this).attr('data-method')+"'>\n"+ "</form>\n" }) .removeAttr('href') .attr('style','cursor:pointer;') .attr('onclick','$(this).find("form").submit();'); });
-
Don't forget to include the .js file in your template after including jQuery.
在包括jQuery之后,不要忘记在模板中包含.js文件。
-
Use classic
link_to()
orlink_to_method()
functions to create links to delete records. Just remember to include the"data-method"="DELETE"
parameter:使用经典的link_to()或link_to_method()函数创建删除记录的链接。只要记住包含“data-method”=“DELETE”参数:
{{ link_to_route('tasks.destroy', 'D', $task->id, ['data-method'=>'delete']) }}
What I like about this that it seems much cleaner than bloating your code with Form::open();
in blade templates.
我喜欢它的一点是,它比用Form::open()膨胀代码要干净得多;在叶片模板。
#4
8
For those looking to create the delete button in Laravel 5:
对于那些想在Laravel 5中创建删除按钮的人:
{!! Form::open(['action' => ['UserController@destroy', $user->id], 'method' => 'delete']) !!}
{!! Form::submit('Delete', ['class'=>'btn btn-danger btn-mini']) !!}
{!! Form::close() !!}
This is similar to Tayler's answer but we use the new blade escape tags ( {!!
and !!}
), we use the Form
facade to generate the button and we use a more elegant approach to link to the controller.
这类似于泰勒的答案,但是我们使用新的刀片退出标记({!!和! !),我们使用表单外观生成按钮,并使用更优雅的方法链接到控制器。
In Laravel < 5 the Forms & HTML package was pulled in automatically. In Laravel 5 we must add this package to composer.json
:
在Laravel < 5中,表单和HTML包被自动拉入。在Laravel 5中,我们必须将这个包添加到composer.json:
...
"required": {
...
"laravelcollective/html": "^5.1"
}
...
Now add the Service Provider and Alias in config/app.php
:
现在在config/app.php中添加服务提供者和别名:
...
'providers' => [
...
Collective\Html\HtmlServiceProvider::class,
],
'aliases' => [
...
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
],
The above will output
上面的输出
<form method="POST" action="https://yourdomain.tld/users/1" accept-charset="UTF-8">
<input name="_method" type="hidden" value="DELETE">
<input name="_token" type="hidden" value="xxxCrAZyT0K3nsTr!NGxxx">
<input class="btn btn-danger btn-mini" type="submit" value="Delete">
</form>
If you are using a different form builder just make sure it generates something similar to the above.
如果您使用的是不同的表单构建器,请确保它生成类似于上面的内容。
#5
8
This is an old questions, but I was just looking for a quick answer and am not satisfied with any of these. What I would suggest to anyone with this same problem is create a new route. Worrying too much about crud compliance is silly, because there is no such thing over HTML; any solution is just shoe-horned to fit, whether it's a hidden form field or a get route.
这是一个老问题,但我只是在寻找一个快速的答案,我对这些都不满意。对于任何有同样问题的人,我的建议是创建一条新的路线。过分担心crud遵从性是愚蠢的,因为在HTML中没有这样的东西;任何解决方案都只是为了适合,不管是隐藏的表单字段还是get路径。
So, in your routes, you likely have something like this:
所以,在你的路线中,你可能有这样的东西:
Route::resource('users', 'UsersController');
The problem with this is that the only way to get to the "destroy" method is to sent a post request which has a hidden input named "_method" and a value of "DELETE".
路线:资源(“用户”、“UsersController”);这样做的问题是,获得“destroy”方法的唯一方法是发送一个post请求,该请求包含一个名为“_method”的隐藏输入和一个名为“DELETE”的值。
Simply add under that line: Route::get('users/{id}/destroy',['as'=>'users.delete','uses'=>'UsersController@destroy']);
只需在该行下面添加:Route:::get('users/{id}/destroy',['as'=>'users.delete','uses'=>'UsersController@destroy']);
Now you have a route you can access from HTML::linkRoute
, Route::url
, or whatever method you please.
现在您有了可以从HTML::linkRoute、route::::url或任何您喜欢的方法访问的路径。
For example: {{ HTML::linkRoute( 'users.delete', 'Delete' , [ 'id' => $user->id ]) }}
例如:{HTML:::linkRoute('users.delete', 'id' => $user->id])}
EDIT
编辑
I want to clarify, though I have explained why it's somewhat silly to bend over backward to fit crud compliance, it is still true that your app will be more secure if changes are made only through POST requests.
我想澄清一下,虽然我已经解释过为什么为了满足crud遵从性而弯腰是有点傻,但是如果只通过POST请求进行更改,您的应用程序仍然会更安全。
#6
4
Want to send a DELETE request when outside of a form?
想在表单外部发送删除请求?
Well, Jeffrey Way created a nice javascript that creates a form for you and to use it you only need to add data-method="delete"
to your delete links.
Jeffrey Way创建了一个很好的javascript为您创建了一个表单,要使用它,您只需将data-method="delete"添加到删除链接中。
To use, import script, and create a link with the data-method="DELETE"
attribute.
要使用、导入脚本并使用data-method="DELETE"属性创建链接。
script :
脚本:
(function() {
var laravel = {
initialize: function() {
this.methodLinks = $('a[data-method]');
this.registerEvents();
},
registerEvents: function() {
this.methodLinks.on('click', this.handleMethod);
},
handleMethod: function(e) {
var link = $(this);
var httpMethod = link.data('method').toUpperCase();
var form;
// If the data-method attribute is not PUT or DELETE,
// then we don't know what to do. Just ignore.
if ( $.inArray(httpMethod, ['PUT', 'DELETE']) === - 1 ) {
return;
}
// Allow user to optionally provide data-confirm="Are you sure?"
if ( link.data('confirm') ) {
if ( ! laravel.verifyConfirm(link) ) {
return false;
}
}
form = laravel.createForm(link);
form.submit();
e.preventDefault();
},
verifyConfirm: function(link) {
return confirm(link.data('confirm'));
},
createForm: function(link) {
var form =
$('<form>', {
'method': 'POST',
'action': link.attr('href')
});
var token =
$('<input>', {
'type': 'hidden',
'name': 'csrf_token',
'value': '<?php echo csrf_token(); ?>' // hmmmm...
});
var hiddenInput =
$('<input>', {
'name': '_method',
'type': 'hidden',
'value': link.data('method')
});
return form.append(token, hiddenInput)
.appendTo('body');
}
};
laravel.initialize();
})();
#7
2
For those looking to create delete button using anchor tag in laravel 5.
对于那些希望在laravel 5中使用锚标记创建delete按钮的人来说。
{!! Form::open(['action' => ['UserController@destroy', $user->id], 'method' => 'DELETE', 'name' => 'post_' . md5($user->id . $user->created_at)]) !!}
<a href="javascript:void(0)" title="delete" onclick="if (confirm('Are you sure?')) { document.post_<?= md5($user->id . $user->created_at) ?>.submit(); } event.returnValue = false; return false;">
<span class="icon-remove"></span>
</a>
{!! Form::close() !!}
#8
1
I tried your code, used it like this and worked:
我尝试了你的代码,像这样使用它,并且成功了:
<a href="{{URL::action('UserController@destroy',['id'=>$user->id]) }}"
onclick=" return confirm('Are you sure you want to delete this?')"
class="btn btn-default">
DELETE </a>
I think that the only problem is in your array:
我认为唯一的问题在于你的阵列:
['id'=>$user->id]
#9
0
{{Form::open(['method'=>'delete','action'=>['ResourceController@destroy',$resource->id]])}}
<button type="submit">Delete</button>
{{Form::close()}}
#1
33
Update 08/21/2017 for Laravel 5.x
Laravel 5.x于2017年8月21日更新
The question asks about Laravel 4, but I include this in case people looking for Laravel 5.x answers end up here. The Form and other helpers aren't available as of 5.x. You still need to specify a method on a form if you are doing something besides GET or POST. This is the current way to accomplish that:
这个问题问的是Laravel 4,但我把它包括在了寻找Laravel 5的人群中。x个答案在这里结束。表单和其他辅助程序无法使用5。x。如果您正在执行除GET或POST之外的操作,仍然需要在窗体上指定一个方法。这是目前实现这一目标的方法:
<form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<!-- other inputs... -->
</form>
You can also use {{ method_field('PUT') }}
instead of writing out the hidden _method
input.
您还可以使用{{method_field('PUT')},而不是写出隐藏的_method输入。
See https://laravel.com/docs/5.4/routing#form-method-spoofing
看到https://laravel.com/docs/5.4/routing form-method-spoofing
Original Answer for Laravel 4
Laravel 4的原始答案
I think when you click the link, it is probably sending a GET request to that end point. CRUD in Laravel works according to REST. This means it is expecting a DELETE request instead of GET.
我认为当你点击链接时,它可能会向那个端点发送一个GET请求。拉拉维尔的克鲁德按照休息工作。这意味着它期望的是删除请求而不是GET。
Here's one possibility from a tutorial by Boris Strahija.
这是鲍里斯·斯特拉希贾(Boris Strahija)的教程中的一种可能性。
{{ Form::open(array('route' => array('admin.pages.destroy', $page->id), 'method' => 'delete')) }}
<button type="submit" class="btn btn-danger btn-mini">Delete</button>
{{ Form::close() }}
This way, you send the request in a form with the DELETE method. The article explains why a traditional link won't work:
通过这种方式,您可以使用DELETE方法将请求发送到表单中。这篇文章解释了为什么传统的链接不起作用:
You may notice that the delete button is inside a form. The reason for this is that the destroy() method from our controller needs a DELETE request, and this can be done in this way. If the button was a simple link, the request would be sent via the GET method, and we wouldn’t call the destroy() method.
您可能注意到,delete按钮位于窗体内部。原因是来自我们的控制器的destroy()方法需要一个DELETE请求,可以这样做。如果按钮是一个简单的链接,那么请求将通过GET方法发送,我们不会调用destroy()方法。
#2
17
An cool ajax solution that works is this:
一个很酷的ajax解决方案是:
function deleteUser(id) {
if (confirm('Delete this user?')) {
$.ajax({
type: "DELETE",
url: 'users/' + id, //resource
success: function(affectedRows) {
//if something was deleted, we redirect the user to the users page, and automatically the user that he deleted will disappear
if (affectedRows > 0) window.location = 'users';
}
});
}
}
<a href="javascript:deleteUser('{{ $user->id }}');">Delete</a>
And in the UserController.php we have this method:
和用户控件。我们有这个方法:
public function destroy($id)
{
$affectedRows = User::where('id', '=', $id)->delete();
return $affectedRows;
}
#3
15
Another "clean" solution is to make it the Rails way as described here:
另一个“干净”的解决方案是使它成为这里描述的Rails方式:
-
Create a new .js file in public and write this function:
在公共场合创建一个新的.js文件并编写这个函数:
$(function(){ $('[data-method]').append(function(){ return "\n"+ "<form action='"+$(this).attr('href')+"' method='POST' style='display:none'>\n"+ " <input type='hidden' name='_method' value='"+$(this).attr('data-method')+"'>\n"+ "</form>\n" }) .removeAttr('href') .attr('style','cursor:pointer;') .attr('onclick','$(this).find("form").submit();'); });
-
Don't forget to include the .js file in your template after including jQuery.
在包括jQuery之后,不要忘记在模板中包含.js文件。
-
Use classic
link_to()
orlink_to_method()
functions to create links to delete records. Just remember to include the"data-method"="DELETE"
parameter:使用经典的link_to()或link_to_method()函数创建删除记录的链接。只要记住包含“data-method”=“DELETE”参数:
{{ link_to_route('tasks.destroy', 'D', $task->id, ['data-method'=>'delete']) }}
What I like about this that it seems much cleaner than bloating your code with Form::open();
in blade templates.
我喜欢它的一点是,它比用Form::open()膨胀代码要干净得多;在叶片模板。
#4
8
For those looking to create the delete button in Laravel 5:
对于那些想在Laravel 5中创建删除按钮的人:
{!! Form::open(['action' => ['UserController@destroy', $user->id], 'method' => 'delete']) !!}
{!! Form::submit('Delete', ['class'=>'btn btn-danger btn-mini']) !!}
{!! Form::close() !!}
This is similar to Tayler's answer but we use the new blade escape tags ( {!!
and !!}
), we use the Form
facade to generate the button and we use a more elegant approach to link to the controller.
这类似于泰勒的答案,但是我们使用新的刀片退出标记({!!和! !),我们使用表单外观生成按钮,并使用更优雅的方法链接到控制器。
In Laravel < 5 the Forms & HTML package was pulled in automatically. In Laravel 5 we must add this package to composer.json
:
在Laravel < 5中,表单和HTML包被自动拉入。在Laravel 5中,我们必须将这个包添加到composer.json:
...
"required": {
...
"laravelcollective/html": "^5.1"
}
...
Now add the Service Provider and Alias in config/app.php
:
现在在config/app.php中添加服务提供者和别名:
...
'providers' => [
...
Collective\Html\HtmlServiceProvider::class,
],
'aliases' => [
...
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
],
The above will output
上面的输出
<form method="POST" action="https://yourdomain.tld/users/1" accept-charset="UTF-8">
<input name="_method" type="hidden" value="DELETE">
<input name="_token" type="hidden" value="xxxCrAZyT0K3nsTr!NGxxx">
<input class="btn btn-danger btn-mini" type="submit" value="Delete">
</form>
If you are using a different form builder just make sure it generates something similar to the above.
如果您使用的是不同的表单构建器,请确保它生成类似于上面的内容。
#5
8
This is an old questions, but I was just looking for a quick answer and am not satisfied with any of these. What I would suggest to anyone with this same problem is create a new route. Worrying too much about crud compliance is silly, because there is no such thing over HTML; any solution is just shoe-horned to fit, whether it's a hidden form field or a get route.
这是一个老问题,但我只是在寻找一个快速的答案,我对这些都不满意。对于任何有同样问题的人,我的建议是创建一条新的路线。过分担心crud遵从性是愚蠢的,因为在HTML中没有这样的东西;任何解决方案都只是为了适合,不管是隐藏的表单字段还是get路径。
So, in your routes, you likely have something like this:
所以,在你的路线中,你可能有这样的东西:
Route::resource('users', 'UsersController');
The problem with this is that the only way to get to the "destroy" method is to sent a post request which has a hidden input named "_method" and a value of "DELETE".
路线:资源(“用户”、“UsersController”);这样做的问题是,获得“destroy”方法的唯一方法是发送一个post请求,该请求包含一个名为“_method”的隐藏输入和一个名为“DELETE”的值。
Simply add under that line: Route::get('users/{id}/destroy',['as'=>'users.delete','uses'=>'UsersController@destroy']);
只需在该行下面添加:Route:::get('users/{id}/destroy',['as'=>'users.delete','uses'=>'UsersController@destroy']);
Now you have a route you can access from HTML::linkRoute
, Route::url
, or whatever method you please.
现在您有了可以从HTML::linkRoute、route::::url或任何您喜欢的方法访问的路径。
For example: {{ HTML::linkRoute( 'users.delete', 'Delete' , [ 'id' => $user->id ]) }}
例如:{HTML:::linkRoute('users.delete', 'id' => $user->id])}
EDIT
编辑
I want to clarify, though I have explained why it's somewhat silly to bend over backward to fit crud compliance, it is still true that your app will be more secure if changes are made only through POST requests.
我想澄清一下,虽然我已经解释过为什么为了满足crud遵从性而弯腰是有点傻,但是如果只通过POST请求进行更改,您的应用程序仍然会更安全。
#6
4
Want to send a DELETE request when outside of a form?
想在表单外部发送删除请求?
Well, Jeffrey Way created a nice javascript that creates a form for you and to use it you only need to add data-method="delete"
to your delete links.
Jeffrey Way创建了一个很好的javascript为您创建了一个表单,要使用它,您只需将data-method="delete"添加到删除链接中。
To use, import script, and create a link with the data-method="DELETE"
attribute.
要使用、导入脚本并使用data-method="DELETE"属性创建链接。
script :
脚本:
(function() {
var laravel = {
initialize: function() {
this.methodLinks = $('a[data-method]');
this.registerEvents();
},
registerEvents: function() {
this.methodLinks.on('click', this.handleMethod);
},
handleMethod: function(e) {
var link = $(this);
var httpMethod = link.data('method').toUpperCase();
var form;
// If the data-method attribute is not PUT or DELETE,
// then we don't know what to do. Just ignore.
if ( $.inArray(httpMethod, ['PUT', 'DELETE']) === - 1 ) {
return;
}
// Allow user to optionally provide data-confirm="Are you sure?"
if ( link.data('confirm') ) {
if ( ! laravel.verifyConfirm(link) ) {
return false;
}
}
form = laravel.createForm(link);
form.submit();
e.preventDefault();
},
verifyConfirm: function(link) {
return confirm(link.data('confirm'));
},
createForm: function(link) {
var form =
$('<form>', {
'method': 'POST',
'action': link.attr('href')
});
var token =
$('<input>', {
'type': 'hidden',
'name': 'csrf_token',
'value': '<?php echo csrf_token(); ?>' // hmmmm...
});
var hiddenInput =
$('<input>', {
'name': '_method',
'type': 'hidden',
'value': link.data('method')
});
return form.append(token, hiddenInput)
.appendTo('body');
}
};
laravel.initialize();
})();
#7
2
For those looking to create delete button using anchor tag in laravel 5.
对于那些希望在laravel 5中使用锚标记创建delete按钮的人来说。
{!! Form::open(['action' => ['UserController@destroy', $user->id], 'method' => 'DELETE', 'name' => 'post_' . md5($user->id . $user->created_at)]) !!}
<a href="javascript:void(0)" title="delete" onclick="if (confirm('Are you sure?')) { document.post_<?= md5($user->id . $user->created_at) ?>.submit(); } event.returnValue = false; return false;">
<span class="icon-remove"></span>
</a>
{!! Form::close() !!}
#8
1
I tried your code, used it like this and worked:
我尝试了你的代码,像这样使用它,并且成功了:
<a href="{{URL::action('UserController@destroy',['id'=>$user->id]) }}"
onclick=" return confirm('Are you sure you want to delete this?')"
class="btn btn-default">
DELETE </a>
I think that the only problem is in your array:
我认为唯一的问题在于你的阵列:
['id'=>$user->id]
#9
0
{{Form::open(['method'=>'delete','action'=>['ResourceController@destroy',$resource->id]])}}
<button type="submit">Delete</button>
{{Form::close()}}