Home > Back-end >  $request->route() returns null in laravel
$request->route() returns null in laravel

Time:06-16

I have this code:

class TotersProviderLoginController extends Controller
{

    private $oauthService;

    public function __construct(Request $request)
    {
        $provider = $request->route()->parameter('provider'); // error here
        if($provider == 'google')
            $this->oauthService = new GoogleOauthService();
        else
            throw new \Exception('Provider '.($provider ?? '').' not supported!');
    }

I have the following routes defined:

Route::get('login/toters/{provider}', 'Accounts\TotersProviderLoginController@redirectToProvider');
Route::get('login/toters/{provider}/redirect', 'Accounts\TotersProviderLoginController@handleProviderCallback');
Route::get('login/toters/{provider}/csrf', 'Accounts\TotersProviderLoginController@getCsrf');
Route::post('login/toters/{provider}/oauth', 'Accounts\TotersProviderLoginController@requestToken');
    

for some reason when I run

php artisan route:list --verbose

I get this error

In TotersProviderLoginController.php line 38:

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Call to a member function parameter() on null

so it's clear that $request->route() is returning null. Why is that? note: I'm using Laravel 5.8

CodePudding user response:

I have debug myself as you mentioned in the question and i found the way where you get the error.

When you run php artisan route:list --verbose command it will debug all routes and also call controller methods of every routes.

In your case what happens when you run command with verbose, route do not have provider default value and that's why it always gives null value.

While you call routes via postman or web it will definitely work, because at that time you have always some value for provider.

Thanks:)

  • Related