laravel-modules api routes don't hit the controller methods

Updated: Feb 09, 2025

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:

  1. 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

  2. Create a new module using the make:module Artisan command. For example, let's create a module called ApiModule.

php artisan make:module ApiModule
  1. 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
  1. 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');
  1. 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());
    }
}
  1. Register the module's service provider in the config/app.php file. Make sure to add the ApiModule\Providers\RouteServiceProvider to the api array under the providers key.
'providers' => [
    // ...
    ApiModule\Providers\RouteServiceProvider::class,
],
  1. 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();