簡體   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