Okay let me explain first. I am sending a PUT request using ajax like this:
//ajax function
$(document).on("click", ".question_no", function(){
current_color = rgb2hex($(this).css('background-color'));
q_index = $(this).attr('id').slice(5);
id_team_packet = $("#id_team_packet").val();
// startTimer();
if (current_color != '#ffc966') {
$(this).css('background-color', "#ffc966");
var status = "orange";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{route('peserta.submit.ans.stat')}}',
method: 'put',
data: {q_index, id_team_packet},
success: function(data){
console.log(data)
}
})
}
})
NOTE I already have my CSRF token setup in my head, which I also include in my ajax setup as you can see below. It works great :). But once I protect that route with a Middleware, like this:
//middleware
public function handle($request, Closure $next)
{
if (Auth::user()) {
if (Auth::user()->role == 3) {
return $next($request);
}
if ($request->ajax()) {
return response()->json(['intended_url'=>'/'], 401);
}
return redirect('/');
}
if ($request->ajax()) {
return response()->json(['intended_url'=>'/'], 401);
}
return redirect('/');
}
//web.php
Route::middleware(['participant_only'])->group(function(){
Route::put('/peserta/submit-answer-status', 'PesertaController@submitAnsStat')->name('peserta.submit.ans.stat');
});
As you can see it only accepts logged in user with a role of '3'. If user tries to log in, it redirects to '/'
. Now I also check if the request is using ajax, which I return a message with code 401. But unfortunately, when the middleware is applied and I ajax it, it returns this error:
message
exception Symfony\Component\HttpKernel\Exception\HttpException
file -\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php
line 203
But if once I remove the middleware it works. I don't know where the problem is. Oh on another note, If I exclude that particular route from verifycsrftoken it returns the right response both with the middleware and without.
My question is, where is the problem and how do I fix it? Thank you :)