【问题标题】:In Laravel, Middleware is ignored in ajax request?在 Laravel 中,ajax 请求中忽略了中间件?
【发布时间】:2016-06-29 04:06:29
【问题描述】:

这是控制器中的方法。它是由 x-editable ajax 请求的。

/**
 * Update base info such as status.
 *
 * @param Request $request
 * @return mixed
 */
public function postUpdateInfo(Request $request)
{
    $this->middleware('recruit');
    dd('passed');
    $recruit = Recruit::find($request->get('pk'));
    list($key, $value) = array($request->get('name'), $request->get('value'));
    if ($recruit->update([$key => $value])) {
        return Response::json(['success' => 1]);
    }
}

在中间件中,代码如下:

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Closure $next
 * @return mixed
 */
public function handle($request, Closure $next, $permission)
{
    die();
    if (Entrust::can($permission)) {
        return $next($request);
    }

    $this->belongsToMe($request, $this->instance);

    return $next($request);
}

但在 chrome 中,我在网络中查看响应。

那么,我认为 ajax 请求中忽略了中间件?太神奇了。

非常感谢。

【问题讨论】:

  • 您可能在控制器的错误位置注册了中间件。查看中间件的文档并查看正确的位置。

标签: php ajax laravel laravel-5 laravel-middleware


【解决方案1】:

您应该将中间件附加到控制器的构造函数中:

public function __construct()
{
    //assign the middleware to all the methods of the controller
    $this->middleware('recruit');
}

或者,如果您只想将其附加到控制器的某个方法,请执行以下操作:

//assign the middleware only to the postUpdateInfo method
$this->middleware('recruit', [ 'only '=> 'postUpdateInfo' ] ]);

【讨论】:

  • @Germy:不客气。如果答案有用,请考虑接受/投票:)
【解决方案2】:

您可以为 404 错误设置回退路由:

Route::fallback('{ CONTROLLER PATH }@error404');

然后,您可以将此方法放入您的控制器中:

public function error404() {
    return view('views.errors.404');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2013-03-07
    • 2021-01-08
    • 1970-01-01
    • 2016-02-23
    • 2011-12-26
    • 2016-12-11
    相关资源
    最近更新 更多