It looks like your middleware is correctly checking the subscription status and trial period, and it is also logging the information. However, the issue seems to be with the redirection and the flash message not being passed correctly.
Here are a few things to check and try:
-
Session Configuration: Ensure that your session is properly configured and that the session driver is set correctly in your
config/session.phpfile. For example, make sure you are not using thearraydriver, which does not persist data between requests. -
Middleware Order: Ensure that your middleware is registered correctly in your
app/Http/Kernel.phpfile. If it is a route middleware, make sure it is applied to the routes correctly. -
Flash Message: Ensure that your view is correctly displaying the flash message. For example, in your Blade template, you should have something like this to display the alert message:
@if (session('alert')) <div class="alert alert-warning"> {{ session('alert') }} </div> @endif -
Middleware Registration: Make sure your middleware is registered in
app/Http/Kernel.php. For example:protected $routeMiddleware = [ // other middleware 'subscribed' => \App\Http\Middleware\Subscribed::class, ]; -
Route Usage: Ensure that the middleware is applied to the routes that require subscription. For example:
Route::group(['middleware' => ['subscribed']], function () { // Your routes that require subscription });
Here is your middleware code with some minor adjustments for clarity:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Log;
class Subscribed
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): Response
{
$user = auth()->user();
$isSubscribed = $user ? $user->subscribed() : false;
$trialExpired = $user ? $user->trialExpired() : true;
Log::info('Subscription status', [
'isSubscribed' => $isSubscribed,
'trialExpired' => $trialExpired,
]);
// Check if user is not subscribed or if the trial has expired
if (!$isSubscribed && $trialExpired) {
$message = !$isSubscribed ? 'Please subscribe to complete this task.' : 'Your trial period has expired. Please subscribe to continue.';
// Add a flash message to the session before redirecting
return redirect()->route('billing')->with('alert', $message);
}
return $next($request);
}
}
If you have checked all the above points and the issue still persists, you might want to debug further by adding more logging or using a tool like Laravel Debugbar to inspect the session data and request flow.
By ensuring that the session is properly configured, the middleware is correctly registered and applied, and the flash message is correctly displayed in your views, you should be able to resolve the issue with the redirection and alert message.