laravel-modules api routes don't hit the controller methods
I'm assuming you're asking about how to properly define and access API routes for controller methods in Laravel using Laravel-Modules. Here's a step-by-step guide to help you achieve that:
-
First, make sure you have installed Laravel-Modules in your Laravel project. You can follow the official documentation to install it: https://laravel-modules.com/docs/5.x/installation
-
Create a new module using the
make:module
Artisan command. For example, let's create a module calledApiModule
.
php artisan make:module ApiModule
- Inside the newly created module directory, create a new controller called
ApiController.php
. This controller will handle the API requests.
php artisan make:controller ApiController --api
- Define your API routes inside the
routes/api.php
file of your Laravel project. Make sure to include the module's namespace in the route definition.
Route::apiResource('users', 'ApiModule\Http\Controllers\ApiController@index');
- Define the controller methods that will handle the API requests. For example, let's create an
index
method that returns a JSON response.
namespace ApiModule\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class ApiController extends Controller
{
public function index()
{
return response()->json(User::all());
}
}
- Register the module's service provider in the
config/app.php
file. Make sure to add theApiModule\Providers\RouteServiceProvider
to theapi
array under theproviders
key.
'providers' => [
// ...
ApiModule\Providers\RouteServiceProvider::class,
],
- Finally, publish the module's routes file using the
php artisan module:publish
command.
php artisan module:publish ApiModule --provider="ApiModule\Providers\RouteServiceProvider"
Now, your API routes should be properly defined and should hit the corresponding controller methods. You can test your API routes by sending a request using a tool like Postman or by making a request from your Laravel application using the Http
facade.
$response = Http::get('api/users');
$users = $response->json();