Laravel Controllers Introduction
15 May 2025 | Category: Laravel
Controllers in Laravel are a core component of the Model-View-Controller (MVC) architecture, acting as the intermediary between the application’s routes, models, and views. They handle HTTP requests, process business logic, interact with models for data operations, and return responses (e.g., views or JSON). This SEO-friendly, plagiarism-free guide introduces Laravel controllers, their purpose, and how to create and use them effectively. Based on Laravel 11 (as of May 2025), this tutorial is designed for beginners and intermediate developers.
What is a Controller in Laravel?
A controller is a PHP class that organizes and manages the logic for handling HTTP requests defined in route files (web.php
or api.php
). Instead of cluttering routes with complex logic, controllers centralize this code, making your application modular, maintainable, and easier to test.
Key Purposes of Controllers
- Handle Requests: Process incoming HTTP requests (GET, POST, etc.).
- Interact with Models: Retrieve or manipulate data using Eloquent models.
- Return Responses: Render views for web routes or return JSON for APIs.
- Organize Logic: Group related request-handling logic into methods.
Why Use Controllers?
Using controllers offers several benefits:
- Separation of Concerns: Keeps routes clean by moving logic to controllers.
- Reusability: Methods can be reused across multiple routes.
- Testability: Controllers are easier to unit-test than route closures.
- Scalability: Organized structure supports large applications.
Creating a Controller
Laravel’s Artisan command-line tool simplifies controller creation. To generate a controller, run:
php artisan make:controller PostController
This creates a PostController.php
file in the app/Http/Controllers/
directory. A basic controller looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
//
}
- Namespace:
App\Http\Controllers
ensures the controller is autoloaded. - Extends Controller: Inherits base functionality from Laravel’s
Controller
class.
Controller with Resource Methods
For RESTful controllers (handling CRUD operations), use the --resource
flag:
php artisan make:controller PostController --resource
This generates a controller with predefined methods:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index() { /* List all resources */ }
public function create() { /* Show create form */ }
public function store(Request $request) { /* Save new resource */ }
public function show($id) { /* Display specific resource */ }
public function edit($id) { /* Show edit form */ }
public function update(Request $request, $id) { /* Update resource */ }
public function destroy($id) { /* Delete resource */ }
}
These methods align with RESTful routing conventions (explained later).
Connecting Controllers to Routes
Controllers are linked to routes in routes/web.php
(for web interfaces) or routes/api.php
(for APIs). Here’s how to connect a controller to a route.
Example: Web Route (web.php
)
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
- Route Definition: Maps GET requests to
/posts
to theindex
method ofPostController
. - Named Route:
posts.index
allows easy URL generation.
Example: API Route (api.php
)
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);
- API Route: Returns JSON, typically for
/api/posts
.
Resource Routes
For CRUD operations, use resource routes to map all RESTful actions in one line:
Route::resource('posts', PostController::class);
This creates seven routes:
HTTP Method | URI | Controller Method | Purpose |
---|---|---|---|
GET | /posts | index | List all posts |
GET | /posts/create | create | Show create form |
POST | /posts | store | Save new post |
GET | /posts/{id} | show | Display specific post |
GET | /posts/{id}/edit | edit | Show edit form |
PUT/PATCH | /posts/{id} | update | Update specific post |
DELETE | /posts/{id} | destroy | Delete specific post |
Writing Controller Logic
Let’s explore how to implement logic in a controller using a PostController
example that interacts with a Post
model.
Example: index
Method (List Posts)
Retrieve all posts and pass them to a view:
use App\Models\Post;
public function index()
{
$posts = Post::all();
return view('posts.index', compact('posts'));
}
- Post::all(): Fetches all posts using Eloquent.
- return view: Renders
resources/views/posts/index.blade.php
with the$posts
variable.
Example: store
Method (Create Post)
Handle a form submission to create a new post:
use Illuminate\Http\Request;
use App\Models\Post;
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
]);
Post::create($validated);
return redirect()->route('posts.index')->with('success', 'Post created!');
}
- Request $request: Captures form input.
- validate: Ensures input meets rules.
- Post::create: Saves the post to the database.
- redirect: Sends the user to the posts list with a success message.
Example: API Controller
For an API, return JSON instead of views:
use App\Models\Post;
public function index()
{
return response()->json(Post::all());
}
Types of Controllers
Laravel supports different controller types based on your needs:
- Basic Controller: A simple class with custom methods (e.g.,
php artisan make:controller MyController
). - Resource Controller: Prebuilt CRUD methods (
--resource
). - API Controller: For JSON responses, often with
--api
flag:
php artisan make:controller Api/PostController --api
Generates index
, store
, show
, update
, and destroy
(excludes create
and edit
for APIs).
- Single Action Controller: Handles one action using the
__invoke
method:
php artisan make:controller ShowPostController --invokable
public function __invoke()
{
// Logic for single action
}
Middleware in Controllers
Middleware filters HTTP requests (e.g., checking authentication). Apply middleware in the controller’s constructor:
public function __construct()
{
$this->middleware('auth')->except(['index', 'show']);
}
- auth: Requires users to be logged in.
- except: Allows unauthenticated access to
index
andshow
.
Alternatively, apply middleware in routes:
Route::get('/posts', [PostController::class, 'index'])->middleware('auth');
Best Practices for Controllers
- Keep Controllers Thin: Move complex logic to services, repositories, or models.
- Use Dependency Injection: Inject models or services via the constructor or method parameters.
public function index(Post $post)
{
return $post->all();
}
- Validate Input: Use form requests or
$request->validate()
for input validation. - Follow REST Conventions: Use resource controllers for consistent CRUD operations.
- Organize Controllers: Group API controllers in
App\Http\Controllers\Api\
. - Name Clearly: Use descriptive names (e.g.,
PostController
for posts).
Conclusion
Controllers are essential for organizing request-handling logic in Laravel, bridging routes, models, and views. By creating controllers with Artisan, connecting them to routes, and implementing methods for web or API responses, you can build robust and maintainable applications. Whether you’re rendering Blade templates or returning JSON, controllers streamline development and adhere to MVC principles.
Next Steps:
- Create a controller:
php artisan make:controller PostController --resource
. - Define routes in
web.php
orapi.php
. - Experiment with Eloquent models and Blade views.
For deeper learning, explore Laravel’s official documentation or connect with the Laravel community on platforms like X. Start building with controllers today!