🛠️ Creating Controllers in Laravel
Controllers in Laravel handle incoming HTTP requests and return responses. You can create them using Artisan commands in several ways depending on your needs.
📄 Basic Controller
Use this to create a simple controller:
php artisan make:controller PageController
File created: app/Http/Controllers/PageController.php
🔁 Add Controller Logic
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PageController extends Controller
{
public function home() {
return view('home');
}
}
Route Example:
Route::get('/home', [PageController::class, 'home']);
☝️ Invokable Controller
Use for controllers with a single action:
php artisan make:controller ContactController --invokable
Inside the controller:
public function __invoke()
{
return view('contact');
}
Route Example:
Route::get('/contact', ContactController::class);
Best for simple "one-action" use cases like contact forms or status checks.
📚 Resource Controller
Use this to auto-generate CRUD methods:
php artisan make:controller ProductController --resource
Generated methods: index, create, store, show, edit, update, destroy
Route Setup:
Route::resource('products', ProductController::class);
This creates full RESTful routes automatically for your controller.
🔐 API-Only Controller
For APIs, you can skip create/edit view-related methods:
php artisan make:controller Api/ProductController --api
This generates controller with only index, store, show, update, destroy
Used with:
Route::apiResource('products', Api\ProductController::class);
No need for Blade views – just return JSON responses.


