Let's say I have these routes:
http:
http:
http:
And I would like the same routes to be accessible from the user domain, pointing to my laravel IP address. Like this:
http:
http:
http:
How is this best achieved?
My current, ugly way
I made my own decision, which is pretty ugly. This is due to a lot of re-code and an unpleasant controller. Here is how I accomplish this:
routes.php
Route::get('/{slug}', ['uses' => 'MyController@show', 'as' => 'page']);
Route::get('/{slug}/page', ['uses' => 'MyController@page', 'as' => 'page.page']);
Route::get('/{slug}/another/{custom_slug}', ['uses' => 'MyController@another', 'as' => 'page.another']);
Route::group(['domain' => '{custom_domain}.{tld}'], function($domain) {
Route::get('/', ['uses' => 'MyController@show', 'as' => 'page.customdomain']);
Route::get('/page', ['uses' => 'MyController@page']);
Route::get('/another/{custom_slug}', ['uses' => 'MyController@another']);
});
MyController.php
class MyController extends Controller {
public function findBySlugOrDomain($domain, $domain_tld, $slug) {
if($domain && $domain_tld) {
$page = $this->page->findByDomain($domain.'.'.$domain_tld)->firstOrFail();
} else {
$page = $this->page->findBySlugOrFail($slug);
}
return $page;
}
public function show($domain = null, $domain_tld = null, $slug = null, $type = 'home', $custom_slug = null)
{
if(str_contains(config('app.url'), $domain . '.' . $domain_tld)) {
return app('App\Http\Controllers\HomeController')->index();
} elseif($domain && !$domain_tld) {
$slug = $domain;
$domain = null;
$domain_tld = null;
} else if($domain && $domain_tld && !$slug) {
$slug = $domain;
$custom_slug = $domain_tld;
$domain = null;
$domain_tld = null;
} else if($domain && $domain_tld && $slug) {
} else if($domain && $domain_tld && $slug) {
$custom_slug = $slug;
}
$page = $this->findBySlugOrDomain($domain, $domain_tld, $slug);
switch ($type) {
case 'page':
return view('page.page', compact('page'));
break;
case 'another':
$anotherPage = $page->another()->whereSlug($custom_slug)->firstOrFail();
return view('page.another', compact('page', 'anotherPage'));
break;
}
return view('page.home', compact('page', 'js_variables'));
}
public function showPage($domain = null, $domain_tld = null, $slug = null) {
return $this->show($domain, $domain_tld, $slug, 'gallery');
}
public function showAnother($domain = null, $domain_tld = null, $slug = null, $custom_slug = null) {
return $this->show($domain, $domain_tld, $slug, 'page', $custom_slug);
}
}
Limitations in this way:
- Lots of snooze code
- Every time I add a new route, I need to update it twice
- Long and clear controller
- A lot of new complexity for the controller, if you need, say, two custom bullets in the URL (
http://mylaravelapp.com/{slug}/another/{custom_slug}/{third_slug})