Today I learned to create a subdomain in Laravel. I'm learning subdomains because I'm planning to create a multitenant-based saas project.
Immediately, the first step I took was to define the hostname and subdomain I wanted.
In order to run in the Windows ecosystem, I then registered the subdomain in hosts C:\Windows\System32\drivers\etc.
I added my domain.
127.0.0.1 notion.az
127.0.0.1 kangmus.notion.az
after that, I also registered the vhost on my local apache. C:\xampp\apache\conf\extra\httpd-vhosts.conf
<VirtualHost 127.0.0.1:80>
DocumentRoot "C:/xampp/htdocs/notion-saas/public"
ServerName *.notion.az
ServerAlias www.notion.az
</VirtualHost>
Then here's the Laravel route script to allow running subdomain routes
Route::domain('{subdomain}.notion.az')->group(function () {
Route::get('/renew', [\App\Http\Controllers\RenewController::class, 'renew'])->name('renew');
});
Then on the controller, the scenario is that I want to retrieve the subdomain name, I use this data to get the current website information.
class RenewController extends Controller
{
public function renew($subdomain)
{
$website = Website::where('subdomain', $subdomain)->firstOrFail();
$merchant = Merchant::where('website_id', $website->id)->firstOrFail();
return view('rootsite::renew', compact('merchant', 'hostname', 'website'));
}
}
Then I run the route in the browser: kangmus.notion.az
Laravel is truly a magic tool. Very helpful in developing SaaS services.