In this episode, we're focusing on cleaning up our middleware and introducing some new middleware to better control access throughout our app, especially when dealing with users' subscription status.
First, we see what happens if an unauthenticated user tries to hit a protected route and how to fix that by making sure all protected routes use the auth
middleware. This ensures users have to log in before seeing sensitive content.
Next, we tackle the logic around subscriptions. For example, there's no point letting a user view subscription plans if they're already subscribed, so we create a RedirectIfSubscribed
middleware. We make this by copying and tweaking our RedirectIfNotSubscribed
middleware, and we test this by applying it to our routes.
We continue by creating additional middleware to handle more specific situations, like only allowing access to the portal or invoice downloads if the user has a valid subscription or Stripe customer ID. There are middleware pieces for things like resuming and cancelling a subscription, ensuring that users can only perform these actions when it's valid (i.e., you can't cancel an already-cancelled subscription). We also set up aliases to make using the middleware in routes a bit nicer and cleaner.
To finish up, we show how to create a custom Blade directive that lets us conditionally show content in our templates based on subscription status — for example, only showing a 'Plans' link if the user is not subscribed. This is implemented as an @notsubscribed
directive in Blade, and we talk through how to set it up and use it.
By the end, you've got a flexible set of middleware and template tools to manage what users can see and do based on their subscription, making your app more robust and your code a bit more maintainable.