Skip to content

Add controllers to a module

To serve posts from a controller in the Blog module, generate PostController and add a route for it. You need an enabled Blog module. A new module already includes BlogController and a Route::resource() route in routes/web.php (see Add routes to a module).

  1. Generate the controller. The command appends Controller automatically.

    Terminal window
    php artisan module:make-controller Post Blog

    This creates Modules/Blog/app/Http/Controllers/PostController.php (Modules\Blog\Http\Controllers\PostController). It extends App\Http\Controllers\Controller with the seven resource methods, and index() returns view('blog::index').

  2. Add a route in Modules/Blog/routes/web.php below the generated resource route.

    Modules/Blog/routes/web.php
    <?php
    use Illuminate\Support\Facades\Route;
    use Modules\Blog\Http\Controllers\BlogController;
    use Modules\Blog\Http\Controllers\PostController;
    Route::resource('blogs', BlogController::class)->names('blog');
    Route::get('posts', [PostController::class, 'index'])->name('blog.posts.index');
  3. Check the result.

    Terminal window
    php artisan route:list --path=posts
    GET|HEAD posts ........ blog.posts.index › Modules\Blog\Http\Controllers\PostController@index

    Start the server with php artisan serve and open http://127.0.0.1:8000/posts. The page renders blog::index (“Hello World” and “Module: Blog”).

Pass a flag to select a different stub (when multiple flags are passed, the first matching flag wins):

To generate Command
An empty controller php artisan module:make-controller Post Blog --plain
A single-action __invoke() controller php artisan module:make-controller PublishPost Blog --invokable

Route an invokable controller by class name:

Route::post('posts/{post}/publish', PublishPostController::class);

To pass model data to a view (using the Post model from Add Eloquent models to a module):

Modules/Blog/app/Http/Controllers/PostController.php
public function index()
{
return view('blog::index', ['posts' => \Modules\Blog\Models\Post::orderBy('id')->get()]);
}

Pass --api to generate a JSON resource controller without create() and edit(). Use a slash in the name to place it in a sub-namespace:

Terminal window
php artisan module:make-controller Api/Post Blog --api

This creates Modules/Blog/app/Http/Controllers/Api/PostController.php (Modules\Blog\Http\Controllers\Api\PostController). Register its routes in Modules/Blog/routes/api.php (see Add routes to a module).