简体   繁体   English

Laravel Auth中间件不适用于POST路由

[英]Laravel Auth Middleware not Working for POST Route

I have a simple form in my site and I want to check if the user is currently logged in before he can post the form. 我的网站上有一个简单的表单,我想检查用户当前是否登录,然后才能发布该表单。 I have put auth middleware in the post route... 我已经将身份验证中间件放在发布路线中...

Route::post('test','SellController@test_mid')->middleware('auth');

My auth middleware... 我的身份验证中间件...

<?php

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax() || $request->wantsJson()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    return $next($request);
}

Here 'login' redirects to my login page. 在这里“登录”重定向到我的登录页面。

The problem is after I hit the login button, the error is... 问题是我按下登录按钮后,错误是...

MethodNotAllowedHttpException in RouteCollection.php line 219: at RouteCollection->methodNotAllowed(array('POST')) in RouteCollection.php line 206 RouteCollection.php第219行中的MethodNotAllowedHttpException:在RouteCollection.php第206行中的RouteCollection-> methodNotAllowed(array('POST'))中

Form... 形成...

{{ Form::open(array('url'=>"/test")) }}=
    <input type="submit" value="submit">
{{ Form::close() }}

But if I set the auth middleware on a GET route, it works fine. 但是,如果我在GET路由上设置auth中间件,则可以正常工作。 In case of a GET , if I am logged out, it leads me to the login page. 如果是GET ,如果我注销了,它将带我到登录页面。 After I provide login credentials and hit the login button it leads me to the desired GET route. 在提供登录凭据并单击登录按钮后,它会将我引导至所需的GET路线。

Make sure your view form uses POST method. 确保您的视图表单使用POST方法。

{{Form::open(array('url'=>'/test', 'method'=>'post'))}}

Please note that $guard variable is NULL by default unless specified. 请注意,除非指定,否则$guard变量默认为NULL。 See your /config/auth.php configuration for available guards. 请参阅/config/auth.php配置以获取可用的防护措施。

Route::post('test', 'SellController@test_mid')->middleware('auth:web'); 

I know this question is an old story, but it seems that you have not the answer yet. 我知道这个问题是一个古老的故事,但看来您还没有答案。 I suggest using middleware inside your controller instead of routes. 我建议在控制器内部使用中间件而不是路由。

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class YourController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function yourFunction(Request $request){
      // your action
    }
}

It works fine for me, either GET or POST method. 无论是GET还是POST方法,它对我来说都很好。

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

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