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).
-
Generate the controller. The command appends
Controllerautomatically.Terminal window php artisan module:make-controller Post BlogThis creates
Modules/Blog/app/Http/Controllers/PostController.php(Modules\Blog\Http\Controllers\PostController). It extendsApp\Http\Controllers\Controllerwith the seven resource methods, andindex()returnsview('blog::index'). -
Add a route in
Modules/Blog/routes/web.phpbelow the generated resource route.Modules/Blog/routes/web.php <?phpuse 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'); -
Check the result.
Terminal window php artisan route:list --path=postsGET|HEAD posts ........ blog.posts.index › Modules\Blog\Http\Controllers\PostController@indexStart the server with
php artisan serveand openhttp://127.0.0.1:8000/posts. The page rendersblog::index(“Hello World” and “Module: Blog”).
Choose another controller type
Section titled “Choose another controller type”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):
public function index(){ return view('blog::index', ['posts' => \Modules\Blog\Models\Post::orderBy('id')->get()]);}Add an API controller
Section titled “Add an API controller”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:
php artisan module:make-controller Api/Post Blog --apiThis 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).
Related
Section titled “Related”module:make-controller: all options and the stub for each.- Configuration:
paths.generator: thecontrollerpath and namespace. - Add routes to a module
- Add middleware to a module