欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

How to pass subdomain variables to controller 子域名值传递 prefix 前缀 有大用 有大用 有大用

Pass parameter to Laravel Middleware

How can I passed a parameter in my middleware? I'm always getting this errorenter image description here

Here are the structure of my middlware

<?php

namespace App\Http\Middleware;

use Closure;

class SubDomainAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $subdomain)
    {
        dd($subdomain); // Just trying to output the result here
        return $next($request);
    }
}

And on the Kernel.php under the $routeMiddleware I added this

'subdomain.access' => \App\Http\Middleware\SubDomainAccess::class,

Now on my web.php route file I added this

Route::group(['domain' => '{subdomain}.' . config('site.domain')], function () {
        Route::get('/', ['as' => 'site.home', 'uses' => 'Site\Listing\ListingController@showListing'])->middleware('subdomain.access');
});

Also I tried this

Route::group(['domain' => '{subdomain}.' . config('site.domain')], function () {
    Route::group(['middleware' => 'subdomain.access'], function () {
        Route::get('/', ['as' => 'site.home', 'uses' => 'Site\Listing\ListingController@showListing']);
    });
});

I tried this but nothings working. The only thing I haven't tried is placing the middleware in my controller constructor. But I don't wan't it that way as I think this is messy and it's more elegant if its within the route file.

Hope you can help me on this. Thanks

 

Ok so I managed to find a way to get the parameters without passing a third parameter on the middleware handle function thanks to this link

So what I did to retrieve the subdomain parameter is this

下面是自己亲自做的 有大用
 

Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function () {
    Route::group(['namespace' => 'Front'],function(){
        Route::resource('/','HomeController');
        Route::resource('categorys','CategoryController');
        Route::resource('articles','ArticleController');
        Route::controller('orders','OrderController');
        Route::get('sitemap','SitemapController@index');
    });
});

Route::group(['prefix' => '{subdomaindir}'], function () {
    Route::group(['namespace' => 'Front'],function(){
        Route::resource('/','HomeController');
        Route::resource('categorys','CategoryController');
        Route::resource('articles','ArticleController');
        Route::controller('orders','OrderController');
        Route::get('sitemap','SitemapController@index');
    });
});

 

//在中间件中 或者 在 构造器里获得它 
$request->route()->parameter('subdomain')  //这个有大用

or if all parameter

$request->route()->parameters()   //这个有大用

可是资源控制器中 show($id){} 
update(Request $request,$id){} 
destory($id){ }
这些方法是 $id 得到的是 路由 {subdomain} 

我在 中间件中 或者 在 构造器里获得它 后 
执行 Request::route()->forgetParameter('subdomain'); 移掉它 就可以了

对于 prefix 前缀 同理







 

['middleware' => 'subdomain.access'] is wrong, try to use ['middleware' => 'subdomain:access'] with a : instead.

https://mattstauffer.co/blog/passing-parameters-to-middleware-in-laravel-5.1

shareimprove this answer
 
   
Sorry but subdomain.access is the name I placed in the kernel as mentioned on my post. And without the 3rd parameter it's actually going inside my custom middleware so meaning the naming is not the issue. If I add the 3rd parameter that's where I get the problem – Madzmar Ullang May 8 at 9:40

Get URI from $request object and then return domain. No need to pass subdomain as params to middleware.

 

namespace App\Http\Middleware;

use Closure;

class SubDomainAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $subdomain)
    {
        $sudomain = $this->getSubDomain($_SERVER['HTTP_HOST']);
        return $next($request);
    }

    /**
     * Get Subdomain name
     * @param $uri
     * @return bool
     */
    private function getSubDomain($uri)
    {
        if(!empty($uri))
        {
            $host = explode('.', $uri);
            if(sizeof($host) > 2)
                return $host[0];
        }

        return false;
    }
}


https://stackoverflow.com/questions/43844108/pass-parameter-to-laravel-middleware



使用php 的方法得到子域名

Route::get('/', function()
{
$url = parse_url(URL::all());
$host = explode('.', $url['host']);
$subdomain = $host[0];
$name = DB::table('name')->where('name',$subdomain)->get();
dd($name);
});

$pieces = explode('.', $request->getHost());//这里也可以得到子域名

function subRoute($route, $params = array())
{
     // retrieve current subdomain if none passed
     if(!isset($params['subdomain'])
     { 
          $params['subdomain'] = array_shift(explode(".",Request::server('HTTP_HOST'))); 
     }
 
     return route($route,$params);
}

$pieces = explode('.', $request->getHost());
    $subdomain = $pieces[0];

$account = array_shift((explode(".", $_SERVER['HTTP_HOST'])));  # get the (probably fake) subdomain of my app domain  $default = array_shift((explode(".", $domain)));


$account = isset($_SERVER['HTTP_HOST'])  ? array_shift((explode(".", $_SERVER['HTTP_HOST'])))  : $default;

 

Getting subdomain within middleware web group in Laravel 5

 

 

picked up Laravel 5.2 some time ago but have never had to use subdomains before.

At the moment I have:

Route::group(['middleware' => ['web']], function () {
    //Login/Logout
    Route::get('/', 'Auth\AuthController@getLogin');
    Route::get('/auth/login', 'Auth\AuthController@getLogin');
    Route::post('/auth/login', 'Auth\AuthController@postLogin');
    Route::get('/logout', 'Auth\AuthController@logout');
});

The thing is, if I want to grab a subdomain (if one exists), I don't then know how to pass it into the '/'route within the Middleware group as well. A lot of the subdomain routing tutorials don't seem to include/reference middleware web (as I have forms on the page and need this functionality also).

Route::group(['middleware' => ['web']], function () {
    //Login/Logout
    Route::get('/', 'Auth\AuthController@getLogin');
    Route::get('/auth/login', 'Auth\AuthController@getLogin');
    Route::post('/auth/login', 'Auth\AuthController@postLogin');
    Route::get('/logout', 'Auth\AuthController@logout');
});

Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('/}', function ($account) {
        //Doesn't work
    });
});

Doesn't work. I just want to get the subdomain (if exists), and stick it in through so I can recall it in my login view.

shareimprove this question
 

1 Answer 正确答案

 

Here is the approach that I use. I wrap all routes inside the web middleware, and wrap most all other routes, with the exception of public pages like homeabout, etc, in the auth middleware. From there, I can grab variable subdomains last, after any constant subdomains (if applicable).

// Encapsulate all routes with web middleware
Route::group(['middleware' => 'web'], function () {

    // Include auth routes
    Route::auth();

    // These routes are require user to be logged in
    Route::group(['middleware' => 'auth'], function () {

        // Constant subdomain
        Route::group(['domain' => 'admin.myapp.localhost.com'], function () {
            // Admin stuff
        });

        // Variable subdomains
        Route::group(['domain' => '{account}.myapp.localhost.com'], function () {

            // Homepage of a variable subdomain
            Route::get('/', function($account) {
                // This will return {account}, which you can pass along to what you'd like
                return $account;
            });
        });
    });

    // Public homepage
    Route::get('/', function () {
        // Homepage stuff
    });
});

It works well with my setup so I hope it helps you towards a solution.

来自  https://stackoverflow.com/questions/34979708/getting-subdomain-within-middleware-web-group-in-laravel-5


 

L5 Sub-Domain middleware

PUBLISHED 2 YEARS AGO BY SWAZ

I am trying to make it so a user goes to a sub-domain to login. The sub-domain would persist throughout the app while they are logged in.

Route::group(['domain' => '{account}.example.com'], function()
{
    Route::get('/', 'HomeController@index');
});

I want to check that the {account} matches the current user. So I setup a global middleware, but how do I grab that value to check if it belongs to the current user? I was thinking something like:

public function handle($request, Closure $next)
{   
    if($route->getParameter('account') != $user->slug)
    {   
        //Abort
    }
    return $next($request);
}

Or is there a better way to go about doing this?

Best Answer(As Selected By Swaz)
Swaz

I got it working by doing this:

public function handle($request, Closure $next)
{   
    $pieces = explode('.', $request->getHost());

    if($pieces[0] != Auth::user()->company->subdomain)
    {
        abort(404);
    }

    return $next($request);
}
Swaz
Swaz
2 years ago(35,145 XP)

I got it working by doing this:

public function handle($request, Closure $next)
{   
    $pieces = explode('.', $request->getHost());//这里也可以得到子域名

    if($pieces[0] != Auth::user()->company->subdomain)
    {
        abort(404);
    }

    return $next($request);
}
 
consigliere

maybe you'll want to use

$request->segments()

in your case maybe

$request->segment(0)
 
rene
rene
2 years ago(8,725 XP)

Isn't there a prettier way to do this nowadays? Anyone? :-)

 
opheliadesign

I second @rene's question - anyone?

 
powerstation

request()->route()->parameters()

 
rizalmx

maybe like this

public function handle($request, Closure $next) { $account = $request->route('account');

if($account != Auth::user()->slug)
{
    abort(404);
}
return $next($request);

}

 

Sign In or create a forum account to participate in this discussion.

来自  https://laracasts.com/discuss/channels/general-discussion/l5-sub-domain-middleware?page=1

普通分类: