Route not found in Laravel even it exists

545 Views Asked by At

I am trying to run an api on postman, I am getting the following error:

Method not found

I created the controller and its route using laravel 5.7, I also checked whether the route exists using php artisan route:list command! I can get the route there. It is listed below is the controller:

<?php

namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Response;
use GuzzleHttp\Client;
use Config;


class EletricityController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    
    public function eletricityToken(Request $request){
      
        $client = new Client();
        $URL = Config('api.authUrl');
        $headers = [
        'Authorization' => 'Bearer <token>'
        ];
        $options = [
        'form_params' => [
        'client_id' => Config('api.client_id'),
        'client_secret' => Config('api.client_secret'),
        'username' => Config('api.username'),
        'password' => Config('api.password'),
        'grant_type' => 'password',
        'scope' => 'read write openid'
        ]];
        $request = new Request('POST', $URL, $headers);
        $res = $client->sendAsync($request, $options)->wait();
        echo $res->getBody();
    }
}

below is the route file:

Route::get('eletricityToken','Api\EletricityController@eletricityToken')->name('eletricityToken');
2

There are 2 best solutions below

5
francisco On

On routes file(web.php/api.php), change the route like:

use App\Http\Controllers\Api\EletricityController;

Route::get('/eletricityToken', [EletricityController::class, 'eletricityToken'])->name('eletricityToken');
0
AdekunleCodez On

You can run php artisan route:list to see the list of routes and their corresponding controller methods.

I can remember that "Route::get('eletricityToken','Api\EletricityController@eletricityToken')->name('eletricityToken');" was allowed in old Laravel projects (version 5, maybe).

Try this

use App\Http\Controllers\Api\EletricityController;

...

Route::get('eletricityToken',[EletricityController::class,'eletricityToken'])->name('eletricityToken');

Please note to add use App\Http\Controllers\Api\EletricityController; immediately after the <?php in your route file.

Best of success