简体   繁体   English

如何修复Laravel令牌不匹配CSRF错误

[英]How to fix Laravel token mismatch CSRF error

In one of my projects in Laravel I have implemented CRUD functionality and in the views for each function I have put a csrf token and a request in depending on the function ie PUT for updating something. 在Laravel的一个项目中,我实现了CRUD功能,并且在每个功能的视图中,我都根据功能(即用于更新某些内容的PUT)放置了一个csrf令牌和一个请求。 I have two problems unfortunately from this. 不幸的是,我有两个问题。 It seems to put @csrf and @method(PUT) in plain text on the html page rather than actually adding the respective functionality to the page. 似乎将@csrf和@method(PUT)放在html页面上的纯文本中,而不是实际在页面中添加相应的功能。 Also for example on the edit page when I try to edit an existing entry in the database, a token mismatch exception error appears and I'm not sure why. 同样,例如,当我尝试编辑数据库中的现有条目时,在编辑页面上,会出现令牌不匹配异常错误,我不确定为什么。

Edit action in the controller: 在控制器中编辑动作:

public function update(Request $request, $id)
{
    $blog = Blog::find($id);
    $blog->title = $request->title;
    $blog->content = $request->content;
    $blog->update();

    return redirect()->route('blog_path', ['blog' => $blog]);
}

Form on edit.blade.php: 在edit.blade.php上的表格:

<form action="{{ route('update_blog_path', ['blog' => $blog->id]) }}" method="POST">
  <input type="hidden" name="_method" value="PUT">
  @csrf

  @method('PUT')

  <div class="form-group">
    <label for="title">Title</label>
    <input type="text" name="title" class="form-control" value="{{ $blog->title}}">
  </div>

  <div class="form-group">
    <label for="content">Content</label>
    <textarea name="content" rows="10" class="form-control">{{$blog->content}}</textarea>
  </div>

  <div class="form-group">
    <button type="submit" class="btn btn-outline-primary">Edit Blog Post</button>
  </div>
</form>

The token mismatch error also doesn't allow me to login and register with standard Laravel authentication so I was wondering if it is a simple fix to solve this error or whether there is something more to it than that? 令牌不匹配错误也不允许我使用标准Laravel身份验证登录和注册,所以我想知道这是否是解决此错误的简单解决方案,或者是否还有其他功能?

Solution #1 - add this meta tag: 解决方案#1-添加此元标记:

<meta name="csrf-token" content="{{ csrf_token() }}">

Solution #2 - add hidden input like this: 解决方案#2-添加隐藏的输入,如下所示:

<input type="hidden" name="_token" value="{{ csrf_token() }}">

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

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