cherrycoding's avatar

Subdomain routing and name in global variable

Hi guys, I am creating a new project where I work with subdomains, I route them dynamically e.g. user1.myapp.com but how can I pass the subdomain (user1) to a variable where I can access globally? For example to retrieve the categories in the Category model I need the user_id which I can get from the subdomain (user1). Can anyone help me to understand how to solve this issue or what's the best practise? Thanks

Regards, Alex

0 likes
4 replies
exwi's avatar

Are you using the built in subdomain routing? https://laravel.com/docs/5.4/routing#route-group-sub-domain-routing

If you look at the example it uses a route group and you set the key {account} for your subdomain. Then any controller in the route group can accept the $account variable in its controller methods like so:

CategoryController.php

public function index($account)
{
    // database query to find user based on $account subdomain
}
cherrycoding's avatar

Yes I am using the built in routing... So I have to find the account_id everytime with from the $account (subdomain) and then find the categories or whatever with this $account_id, right? Or can I make global var $account_id in the router?

Thanks Regards, Alex

exwi's avatar

You can also bind a custom route pattern in routeserviceprovider.php which will find your account and return the account model to be used in your controllers.

cherrycoding's avatar

Can u please give me an example? I would like to create a global variable from subdomain with account_id and create a global scope in the model for account_id = $account_id

Thanks

Regards, Alex

Please or to participate in this conversation.