简体   繁体   中英

Laravel pass route url parameter as null to controller

Short problem description:

How do I write this part: $provider = "" in this route:

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

Long version:

I would like to rewrite this into a controller:

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();
}));

I've got this so far:

Route.php

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

controller:

/**
     * 
     */
    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;
    }

You're on the right track! To use an optional route parameter, you give it a default value in your controller, just like you did in your function.

public function hybridauth($provider = null)

Then you can do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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