php CRUD Laravel 4 如何链接销毁?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19643483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CRUD Laravel 4 how to link to destroy?
提问by helloworld
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))}}
回答by Tayler
Update 08/21/2017 for Laravel 5.x
2017 年 8 月 21 日更新 Laravel 5.x
The question asks about Laravel 4, but I include this in case people looking for Laravel 5.x answers end up here. The Form helper (and some others) 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 请求。Laravel 中的 CRUD 根据 REST 工作。这意味着它期待 DELETE 请求而不是 GET。
Here's one possibility from a tutorialby 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.
您可能会注意到删除按钮位于表单内。这样做的原因是我们控制器的 destroy() 方法需要一个 DELETE 请求,这可以通过这种方式完成。如果按钮是一个简单的链接,请求将通过 GET 方法发送,我们不会调用 destroy() 方法。
回答by paulalexandru
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:
在 UserController.php 中,我们有这个方法:
public function destroy($id)
{
$affectedRows = User::where('id', '=', $id)->delete();
return $affectedRows;
}
回答by paulalexandru
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:
$(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.
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_route('tasks.destroy', 'D', $task->id, ['data-method'=>'delete']) }}
公开创建一个新的 .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();'); });
在包含 jQuery 之后,不要忘记在模板中包含 .js 文件。
使用经典
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();
在刀片模板中膨胀你的代码要干净得多。
回答by theaceofthespade
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 没有这样的事情;任何解决方案都只是勉强适合,无论是隐藏的表单字段还是获取路径。
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".
Route::resource('users', 'UsersController');
问题在于,获得“销毁”方法的唯一方法是发送一个 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', '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 请求进行更改,您的应用程序仍然会更安全。
回答by DutGRIFF
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.
这类似于 Tayler 的答案,但我们使用新的刀片转义标签({!!
和!!}
),我们使用Form
外观来生成按钮,我们使用更优雅的方法来链接到控制器。
In Laravel < 5 the Forms & HTML packagewas pulled in automatically. In Laravel 5 we must add this package to composer.json
:
在 Laravel < 5 中,Forms & 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.
如果您使用不同的表单构建器,请确保它生成与上述类似的内容。
回答by chebaby
Want to send a DELETE request when outside of a form?
想要在表单之外发送 DELETE 请求?
Well, Jeffrey Waycreated 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.
要使用,请导入script,并使用该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();
})();
回答by Konsole
For those looking to create delete button using anchor tag in laravel 5.
对于那些希望在 laravel 5 中使用锚标记创建删除按钮的人。
{!! 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() !!}
回答by Laura Chesches
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]
回答by Neo
{{Form::open(['method'=>'delete','action'=>['ResourceController@destroy',$resource->id]])}}
<button type="submit">Delete</button>
{{Form::close()}}