Controllers
Where your app’s logic lives — keeping routes clean and code organised.
What you will learn
- Generate a controller
- Write controller methods
- Return views with data
Controllers hold the logic
Rather than cramming logic into routes, put it in controllers. Generate one with artisan, then write methods.
php artisan make:controller ProductControllerThis artisan command creates a ready-made, empty controller file at app/Http/Controllers/ProductController.php. You do not write the boilerplate by hand — artisan scaffolds it, and you just fill in the methods.
Now look inside that controller. Each method is one action your app can do — here, index lists products and show displays a single one:
// app/Http/Controllers/ProductController.php
class ProductController extends Controller
{
public function index()
{
$products = ['Keyboard', 'Mouse', 'Monitor'];
return view('products.index', ['products' => $products]);
}
public function show($id)
{
return view('products.show', ['id' => $id]);
}
}Walking through it: index() builds a list of products (here a simple array — later it will come from the database) and then returns a view. The second argument ['products' => $products] is the data being handed to the view: the key 'products' becomes a $products variable inside the Blade template. show($id) receives the route parameter $id and passes it along to its own view so the page knows which product to display.
Note: The view(...) call loads resources/views/products/index.blade.php and passes it data. That data appears in the Blade template — covered next.
Q. What is the main job of a controller?
✍️ Practice
- Generate a controller and add an
indexmethod that returns a view with data. - Point a route to it.
🏠 Homework
- Build a PostController with index and show methods.