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
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
orphp artisan cache:clear
.The issue is happening because you might have cached your routes.
Route Definition
In your routes/api.php file, you currently have a route that directly returns a string:
This route directly returns ‘get all continents’ as a response when you access http://localhost/api/v1/continent.
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:
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:
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.