A controller is the class that receives a request and coordinates the application’s response.
In Laravel, the philosophy is: “The routes file (web.php) should only be an index, not the entire book”. Routes should point to a Controller, and the Controller is the one that does the work.
Creating your first controller
Don’t create it by hand. Use your Artisan assistant:
php artisan make:controller ProductControllerThis generates a file in app/Http/Controllers/ProductController.php. It’s an empty class where we will place our functions (called methods).
Moving the logic: from route to controller
Let’s create a method to display a list of products.
A. In the Controller (ProductController.php):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
// Method to display the list
public function index()
{
$products = ['Keyboard', 'Mouse', 'Monitor']; // Simulating database data
// Return the view passing the data
return view('products.list', ['items' => $products]);
}
}B. In the Routes file (web.php):
Now the route is very clean. It just says “If you go to /products, call the index method of ProductController”.
use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;
// Syntax: [Class::class, 'MethodName']
Route::get('/products', [ProductController::class, 'index']);The Request object: goodbye to $_POST and $_GET
Here comes one of the biggest changes compared to classic PHP. Instead of looking for global variables like $_POST['name'], Laravel gives you a Request Object that contains all the HTTP request information in an organized and secure way.
How is it used? (Dependency Injection)
Simply “request” the object in your function parameters. Laravel is so clever that, upon seeing you ask for Request $request, it automatically injects it filled with data.
Example: Process a contact form
Suppose you have an HTML form that sends name and email via POST.
// In the Controller
public function save(Request $request)
{
// Old PHP (DO NOT DO THIS):
// $name = $_POST['name'];
// LARAVEL (Correct Way):
// 1. Get a specific piece of data
$name = $request->input('name');
// 2. Get the entire form as an array
$data = $request->all();
// 3. Check if a piece of data is present (true/false)
if ($request->has('subscription')) {
// ...
}
// 4. Get the user's IP
$ip = $request->ip();
// Logic to save (we'll see this later)...
// 5. Redirect to another page
return redirect('/thank-you')->with('message', 'Received!');
}Why is it better to use Request?
- Uniform access:
Requestmakes it easy to read data, files, headers, and metadata. It does not automatically validate or sanitize: you must apply validation rules and escape the output. - Uniformity: It doesn’t matter if the data comes via JSON (API), a POST form, or a GET URL. The
$request->input('data')method works the same for all. - Useful methods: It has built-in functions like
$request->isMethod('post'),$request->file('photo'), etc.