What Are Controllers in Laravel?
Controllers are classes defined in the App\Http\Controllers
namespace. They group related request-handling logic into a single class, improving code organization.
Types of Controllers
Single-Action Controllers
Controllers with a single method, typically invoked using the __invoke
method.
php artisan make:controller SingleActionController --invokable
Resource Controllers
Basically Resource controllers create for crud operations (Create, Read, Update, Delete) operations.
php artisan make:controller BlogController --resource
Creating Controllers
To create a new controller:
php artisan make:controller BlogController
Routes and Controllers
You can map routes to controller methods using Route::get
, Route::post
, etc.
use App\Http\Controllers\BlogController; Route::get('/blogs', [BlogController::class, 'index']);
For resource routes:
use App\Http\Controllers\BlogController; Route::resource('blogs', BlogController::class);
Controller Methods
A standard resource controller includes the following methods:
index()
- Display a listing of the resource.create()
- Show the form for creating a new resource.store()
- Save a newly created resource in storage.show($id)
- Display the specified resource.edit($id)
- Show the form for editing the specified resource.update($id)
- Update the specified resource in storage.destroy($id)
- Remove the specified resource from storage.
Example: Blog Controller
namespace App\Http\Controllers; use App\Models\Blog; use Illuminate\Http\Request; class BlogController extends Controller { public function index() { $blogs = Blog::latest()->get(); return view('blogs.index', compact('blogs')); } public function show($id) { $blog = Blog::findOrFail($id); return view('blogs.show', compact('blog')); } }
Integrating with Tailwind CSS
Tailwind CSS Blog Index View:
<!DOCTYPE html> <html lang="en"> <head> <title>Blogs</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body class="bg-gray-100 text-gray-800"> <div class="container mx-auto px-4 py-8"> <h1 class="text-4xl font-bold mb-8 text-center">Blog Posts</h1> <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3"> @foreach($blogs as $blog) <div class="bg-white rounded-lg shadow-md overflow-hidden"> <img src="{{ $blog->thumbnail }}" alt="Thumbnail" class="w-full h-48 object-cover"> <div class="p-4"> <h2 class="text-2xl font-semibold mb-2">{{ $blog->title }}</h2> <p class="text-gray-600 mb-4">{{ Str::limit($blog->description, 100) }}</p> <a href="{{ route('blogs.show', $blog->id) }}" class="text-blue-500 hover:underline"> Read More </a> </div> </div> @endforeach </div> </div> </body> </html>
Best Practices
- Use resource controllers for RESTful APIs.
- Group routes by functionality for better organization.
- Use middleware for authentication and authorization.
- Avoid placing business logic in controllers—use services or repositories instead.
- Utilize route model binding for cleaner code.