Germey
Germey

Reputation: 640

In Laravel, Middleware is ignored in ajax request?

This is the method in controller. It is requested by 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]);
    }
}

In middleware, codes below:

/**
 * 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);
}

But in chrome, I view the response in network.

enter image description here

So, I think middleware is ignored in ajax request? So amazing.

Thanks a lot.

Upvotes: 0

Views: 2196

Answers (2)

Rif Rocket
Rif Rocket

Reputation: 1

You can set a fallback route for 404 errors:

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

And then, you can put this method in your controller:

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

Upvotes: 0

Moppo
Moppo

Reputation: 19285

You should attach your middleware in the controller's construtor:

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

Or, if you want attach it only to some method of your controller, do:

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

Upvotes: 1

Related Questions