I have this middleware in my project, that sometimes, gives me some problems on my live server, and I don't know why, but just sometimes, and not all the times that it is triggered. This is the error:
Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Illuminate\Routing\Redirector given
The error is triggered by the return $next($request);
, bellow is my middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Event;
class EventOwner
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(isset($request["id_event"])){
$event_id = $request["id_event"];
$events = Event::where('id', $event_id)->where('user_id', Auth::user()->id)->first();
if(isset($events)){
if($events->id == $event_id){
return $next($request);
}else{
$message = '401 - NOT AUTHORIZED';
return response(view('errors.not-auth', compact('message')), 401);
}
}else{
$message = '401 - NOT AUTHORIZED';
return response(view('errors.not-auth', compact('message')), 401);
}
}
}
}
I already changed my return to a return redirect()->route('register');
, to return a redirector object, but nothing happened.
I tried to improve my code too, I changed the code to this:
public function handle(Request $request, Closure $next)
{
$event_id = $request["id_event"];
if (!$event_id) {
abort(404);
}
$events = Event::where('id', $event_id)->where('user_id', Auth::user()->id)->first();
if ($events->isEmpty()) {
$message = '401 - NOT AUTHORIZED';
return response()->view('errors.not-auth', compact('message'), 401); // Create response with error view
}
return $next($request);
}
although this is a good improvement, I still don't know how to replicate the error, or what triggered the error.
I tried to php artisan config:clear
in my live server but, again, I don't know if it works, because I cant replicate the error.
Can someone help me fix this issue, and help me find what triggered the error? Thank you in advance.
Thats not a middleware related problem it is router/controller level problem. After your middleware is finished you do some redirects at your router/controller and your return redirect();
is probably empty. Check your redirects after middleware.