Reputation: 111
I'm building a new application in Laravel 5.5 which will rely heavily on its subdomain names.
I have successfully set a route group for subdomain routing, but eventually I'll need the subdomain name variable be available for every controller and for every view.
I already have a custom View Composer, where I pass session variables to every view. How can I make the subdomain name available for the View Composer? I don't think I can access subdomain through Request object.
Also, is it possible to pass subdomain name to every controller and its methods without needing to specify parameter in every method?
Currently, my routing looks like:
Route::domain('{sub}.something.com')->group(function () {
Route::prefix('admin')->group(function ($sub) {
Route::get('/', 'AdminController@methodroute1')->name('admin.route1');
Route::get('/route2', 'AdminController@methodroute2')->name('admin.route2');
Route::post('/', 'AdminController@methodroute3')->name('admin.route3');
/snip
But this way, I need to define every controller method as
public function method($sub){}
Even worse, call every named route and pass the $sub parameter to every view like this:
public function method($sub){
if(Sentinel::check()){
return redirect()->route('admin.route1',$sub);
} else {
return view('admin.route2')->with('sub',$sub);
}
}
and in a view:
{{ route('admin.route1',$sub) }}
I understand if I really need to pass the $sub variable to the views and to the controllers, but I'd really prefer to automatize it by using View Composer:
public function __construct()
{
$this->user = session('user');
$this->userdata = session('userdata');
$this->permissions = session('permissions');
}
public function compose(View $view)
{
$view->with(['user' => $this->user, 'userdata' => $this->userdata, 'permissions' => $this->permissions]);
}
So how do I get $sub into my View Composer to be able to define it as:
$this->subdomain = $sub_from_somewhere
Or am I doing this wrong? I couldn't find any more efficient way to build the app with subdomain logic in it.
Thank you very much.
Upvotes: 1
Views: 4766
Reputation: 110
This is a simple solution:
Route::current()->parameter('sub')
You can use this in the Controller or pass to the Views.
Upvotes: 0
Reputation: 8663
You can use helper function request() that gives you access to all current request parameters. In your case you can access "sub" value in your blade like that:
{{request("sub")}}
Upvotes: 1