Laravel BasicsCore· 35 min read

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.

Generate a controller
php artisan make:controller ProductController

This 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:

A controller passing data to views
// 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?

Answer: Controllers contain the logic: they receive the request, use models for data, and return a view — keeping routes thin.

✍️ Practice

  1. Generate a controller and add an index method that returns a view with data.
  2. Point a route to it.

🏠 Homework

  1. Build a PostController with index and show methods.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →