I am creating an API Laravel project and it seems that there an error I can’t find.
I want to get data from the table ‘units’.
These are the codes:
bootstrap/app.php
<?php
use IlluminateFoundationApplication;
use IlluminateFoundationConfigurationExceptions;
use IlluminateFoundationConfigurationMiddleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
api.php
<?php
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
use AppHttpControllersUnitController;
// Define the API routes for units
Route::apiResource('units', UnitController::class);
controller
public function index()
{
return Unit::all();
}
When I try to test it in Postman with the link http://localhost/api/units
it says
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache/2.4.58 (Win64) OpenSSL/3.1.3 PHP/8.2.12 Server at localhost Port 80</address>
</body>
</html>
I checked the database .env file
APP_NAME=SKYCENTRAL
APP_ENV=local
APP_KEY=base64:havtW5AahJjp4acK6Wg8PvRewVywLlwzjcp9xdA2NnQ=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=skycentral
DB_USERNAME=root
DB_PASSWORD=
I tried php artisan route:list
GET|HEAD / .......................................................................................................................................................... generated::Tn7gBH3CyKBwZe5V
GET|HEAD up ......................................................................................................................................................... generated::AsPiJE7sim8PezPd
3
Answers
It would help if you optimized after each change in routes.
OR
You need to register the
api.php
routes inbootstrap/app.php
You can simply do that with a command in laravel 11
First need to change in .env file like APP_URL
Since Laravel takes the api prefix by default in the api route, the api.php route file needs to have the api prefix removed.
Your api url will after that look like that.