skip to Main Content

I’m working on a project using laravel 10 that uses REST API but I’m getting a 404 not found error when I tried to test the url http://localhost/api/v1/continent with GET request in Postman.

this is my routes/api.php:

Route::prefix('v1')->name('v1.')->group(function() {
    Route::get('continent', function() {
        return 'get all continents';
    });
});

this is the code in my App/Http/Controllers/Api/V1/ContinentController.php:

<?php

namespace AppHttpControllersApiV1;

use AppModelsContinent;
use IlluminateHttpRequest;
use AppHttpControllersController;

class ContinentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $list = Continent::all();
        // dd($list);

        return response()->json($list);
    }
}

what am I doing wrong? any help is appreciated.

2

Answers


  1. Check if you have a routes.php file in bootstrap/cache folder. If it is you can delete it or you can run command php artisan routes:clear or php artisan cache:clear.
    The issue is happening because you might have cached your routes.

    Login or Signup to reply.
    1. Route Definition
      In your routes/api.php file, you currently have a route that directly returns a string:

       Route::prefix('v1')->name('v1.')->group(function() {
         Route::get('continent', function() {
           return 'get all continents';
         });
       });
      

    This route directly returns ‘get all continents’ as a response when you access http://localhost/api/v1/continent.

    1. Controller Method
      In your ContinentController, you have a method index() which is supposed to fetch all continents from the database and return them as JSON:

       namespace AppHttpControllersApiV1;
       use AppModelsContinent;
       use IlluminateHttpRequest;
       use AppHttpControllersController;
      
      class ContinentController extends Controller{
      
      public function index()
      {
         $list = Continent::all();
         return response()->json($list);
      }
      }
      
    2. Connecting Route to Controller

    To fix the issue and correctly route requests to your controller method, you should modify your route definition to point to the index() method of ContinentController:

    Route::prefix('v1')->name('v1.')->group(function() {
        Route::get('continent', [AppHttpControllersApiV1ContinentController::class, 'index']);
    });
    

    Explanation:

    Route Definition:
    The updated route definition uses the Route::get method to map the /api/v1/continent endpoint to the index() method of ContinentController.

    Controller Method:
    The index() method in ContinentController retrieves all continents using Continent::all() and returns them as a JSON response using Laravel’s response()->json() helper.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search