Developer Snippet Diary

create controller in subfolder

In Laravel, controllers are used to handle incoming HTTP requests and perform actions based on those requests. By default, Laravel creates controllers in the "app/Http/Controllers" directory, but it is also possible to organize controllers into subfolders for better organization.

To create a controller in a subfolder, follow these steps:

1.Create a new folder inside the "app/Http/Controllers" directory. For example, you can create a folder called "Admin".

2. Create a new controller inside the subfolder you just created. For example, you can create a controller called "AdminController" inside the "Admin" folder. To create a controller, you can use the "php artisan make:controller" command in the terminal:

php artisan make:controller Admin/AdminController

3. In the new controller, define the methods that will handle incoming HTTP requests. For example, you can define a method called "testo" that will handle GET requests to the "/admin/testo" URL:

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
class AdminController extends Controller
{
    public function testo()
    {
        return 'This is a test controller in a subfolder!';
    }
}

4. In your routes file, use the "Route::controller" method to define routes that will be handled by the controller. In the example below, we're using the "Route::controller" method to map all HTTP methods to the "AdminController" controller in the "Admin" subfolder. 

Route::controller(\App\Http\Controllers\Admin\AdminController::class)->group( function () {
    Route::get('/admin/testo', 'testo');
});

You can now access the "testo" method in the "AdminController" controller by visiting the "/admin/testo" URL in your browser.

That's it! You've successfully created a controller in a subfolder and defined routes that are handled by that controller. By organizing your controllers into subfolders, you can make your codebase easier to navigate and maintain.

Posted by: R GONDAL
Email: rizikmw@gmail.com