In Laravel, controllers are responsible for handling incoming HTTP requests and executing the appropriate logic to generate a response. They act as an intermediary between the routes defined in your application and the actual logic that processes the requests.
Controllers are created using the Artisan command-line tool:
php artisan make:controller YourControllerName
Controllers consist of methods that correspond to actions in your application.
class YourControllerName extends Controller {
public function method1() {
// Logic
}
public function method2() {
// Logic
}
}
Route to controller methods in routes/web.php
.
Route::get('/route', [YourControllerName::class, 'method1']);
Laravel supports dependency injection in controllers.
public function method(Request $request) {
// Logic
}
Controllers can return various responses like views, JSON, redirects, etc.
public function method() {
return view('view_name');
}
Apply middleware to controllers or specific methods.
public function __construct() {
$this->middleware('auth');
}
Controllers act as the bridge between your application's HTTP requests and the underlying logic that handles those requests, allowing you to maintain a structured and organized codebase in your Laravel application.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
// Method to show all users
public function index()
{
$users = User::all();
return view('users.index', ['users' => $users]);
}
// Method to show a specific user
public function show($id)
{
$user = User::find($id);
return view('users.show', ['user' => $user]);
}
// Method to store a new user
public function store(Request $request)
{
// Validate request data
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users|max:255',
'password' => 'required|string|min:8',
]);
// Create a new user
$user = User::create($validatedData);
return redirect()->route('users.show', $user->id);
}
}
After creating a controller, you need to define routes that point to the controller methods. You can define routes in the routes/web.php file.
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index'])->name('users.index');
Route::get('/users/{id}', [UserController::class, 'show'])->name('users.show');
Route::post('/users', [UserController::class, 'store'])->name('users.store');