In this episode, we're cleaning up the way we fetch users based on the subdomain they visit. Previously, we were manually grabbing the user from the database in each route — definitely not ideal.
So, we kick things off by setting up a dedicated HomeController for our subdomain routes, keeping our code organized and tidy. After creating the controller (and putting it in its own subdomain folder), we talk about a much more convenient way to pull in the user: route model binding.
Laravel's route model binding allows us to directly inject a user model into our controller based on a specific route parameter. But, instead of the default (fetching by id), we tweak it to use the user's subdomain column. That way, when someone visits something like alex.laravel-user-subdomains.test
, the corresponding user gets automatically fetched from the database. It makes everything smoother and means we don't have to do the manual database lookups anymore.
From here, any new routes or controllers that need the user can just use the same pattern, and Laravel will handle pulling in the right user for us. It’s much cleaner and way more scalable!