简体   繁体   English

如何修复删除按钮在Laravel 5.7中不起作用?

[英]How to fix delete button not working in Laravel 5.7?

I'm trying to make a delete button in Laravel, but it redirects me to a white page. 我正在尝试在Laravel中创建一个删除按钮,但是它将我重定向到白页。 this is the html code for the delete button (it's an icon): 这是删除按钮的html代码(它是一个图标):

<a class="icon" href="{{ route('capteurs.destroy', $capteur->id)}}" data-balloon="Supprimer" data-balloon-pos="right">
    <i class="fe fe-trash-2" ></i>
</a>

destroy function in the controller class: 在控制器类中destroy功能:

public function destroy($id)
{
  $capteur = Capteur::find($id);
  $capteur->delete();
  return redirect('/capteurs')->with('success', 'Capteur Supprimé');
}

I'm supposed to be redirected to /capteurs which is this page: 我应该被重定向到/capteurs这是此页面: 在此处输入图片说明

Instead i get redirected here, and the element i wanna delete is still there: 相反,我在这里被重定向了,我想要删除的元素仍然在那里:

在此处输入图片说明

Edit: Routes for capteurs 编辑:Capteurs的路线

Route::resource('capteurs', 'CapteurController');

I think you should make a form for that: 我认为您应该为此填写表格:

<form method="POST" action="{{ route('capteurs.destroy', $capteur->id)}}"
  @csrf
  @method('DELETE')
  <a class="icon" data-balloon="Supprimer" data-balloon-pos="right">
  </a>
  <button type="submit"><i class="fe fe-trash-2" ></i></button>
</form>

You need to add a form around your anchor tag and next thing you need is a DELETE request instead of GET . 您需要在锚标记周围添加一个form ,接下来需要做的是DELETE请求而不是GET You can try the below code: 您可以尝试以下代码:

<form action="{{ route('capteurs.destroy', $capteur->id) }}" method="POST">
    {{ method_field('DELETE') }}
    {{ csrf_field() }}
    <button type='submit' class="btn btn-danger" ><i class="fe fe-trash-2" ></i></button>
</form>

If you really want it to do with the anchor tag then give a specific id to your anchor tag and do an ajax request! 如果您真的希望它与锚标记一起使用,则给锚标记提供一个特定的id并执行ajax请求!

You're currently linking to your destroy page like its a GET request, while it should be a POST request. 您当前正在链接到销毁页面,例如它的GET请求,而它应该是POST请求。 If execute php artisan route:list it will show information on the routes. 如果执行php artisan route:list ,它将显示有关路由的信息。

To fix this: 要解决此问题:

<form action="{{ URL::route('capteurs.destroy', $capteur->id) }}" method="POST">
    <input type="hidden" name="_method" value="DELETE">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <button><i class="fe fe-trash-2" ></i></button>
</form>

You'll probably have to edit styling a bit though 您可能需要编辑一些样式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM