繁体   English   中英

Laravel将路由URL参数作为null传递给控制器

[英]Laravel pass route url parameter as null to controller

问题简述:

我如何写这部分: $provider = ""在这条路线中:

Route::get('/connect/{provider?}', array('as' => 'hybridauth', 'uses' => 'AuthController@hybridauth'));

长版:

我想将其重写为控制器:

Route::get('connect/{provider?}', array("as" => "hybridauth", function($provider = "")
{
    // check URL segment
    if ($action == "auth") {
        // process authentication
        try {
            Hybrid_Endpoint::process();
        }
        catch (Exception $e) {
            // redirect back to http://URL/social/
            return Redirect::route('hybridauth');
        }
        return;
    }
    try {
        // create a HybridAuth object
        $socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php');
        // authenticate with Google
        $provider = $socialAuth->authenticate("google");
        // fetch user profile
        $userProfile = $provider->getUserProfile();
    }
    catch(Exception $e) {
        // exception codes can be found on HybBridAuth's web site
        return $e->getMessage();
    }
    // access user profile data
    echo "Connected with: <b>{$provider->id}</b><br />";
    echo "As: <b>{$userProfile->displayName}</b><br />";
    echo "<pre>" . print_r( $userProfile, true ) . "</pre><br />";

    // logout
    $provider->logout();
}));

到目前为止,我已经做到了:

Route.php

Route::get('/connect/{provider?}', array('as' => 'hybridauth', 'uses' => 'AuthController@hybridauth'));

控制器:

/**
     * 
     */
    public function hybridauth($provider)
    {
        if (isset($provider))
        {
            try
            {
                Hybrid_Endpoint::process();
            }
            catch (Exception $e)
            {
                // redirect back to http://URL/connect/
                return Redirect::route('hybridauth')->with('provider', $provider);
            }
            return;
        }

        try
        {
            $socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php');
            $haProvider = $socialAuth->authenticate($provider);
            $userProfile = $haProvider->getUserProfile();
        }
        catch(Exception $e)
        {
            // exception codes can be found on HybBridAuth's web site
            return $e->getMessage();
        }

        return $userProfile;
    }

您在正确的轨道上! 要使用可选的route参数,请在控制器中为其提供默认值,就像在函数中一样。

public function hybridauth($provider = null)

那你可以做

if (is_null($provider)) { ... }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM