Skip to content

🎮 Controllers

Controllers are regular PHP classes responsible for handling HTTP requests and returning responses to the user.

They help separate application logic: routes define which URL to handle, while the controller determines what to do when that URL is called.

🚀 Quick Start

🔍 Why Use Controllers?

Imagine a user opens the "About Us" page:
https://site.com/about

We need to:

  1. 📥 Catch this request.
  2. 🧠 Prepare data (e.g., page content).
  3. 📤 Return an HTML page to the user.

To achieve this, we create:

  • 📌 A route – specifies which URL to respond to.
  • 🧱 A controller – a class that processes this request.

🛠 Step 1: Create a Route

Open the routes file (e.g., routes/web.php) and add:

php
Route::get('/about', 'AboutController@index');

Here:

  • /about – the path in the address bar.
  • 'AboutController@index' – means: call the index method in the AboutController class.

🧱 Step 2: Create the Controller

Now, let’s create the controller in the App\Http\Controllers folder:

php
<?php  

namespace PageBlocks\App\Http\Controllers;  

class AboutController extends Controller  
{  
    public function index()  
    {  
        return view('about'); // Render the about.tpl template  
    }  
}

What’s happening here:

  • AboutController – a regular PHP class.
  • index() – the method called when visiting /about.
  • view('about') – returns the HTML template about.tpl.

🧠 What Does a Controller Do?

A controller:

  • Receives the browser request,
  • Executes necessary logic (e.g., fetches data from the database),
  • Returns a response – HTML, JSON, or plain text.

It acts like a dispatcher:
Request comes in → Checks what’s needed → Returns the required information.

💡 Example with a Parameter

Suppose we want to display a user by ID:

php
Route::get('/user/{id}', 'UserController@show');

Controller:

php
class UserController extends Controller  
{  
    public function show($id)  
    {  
        return "User with ID: $id";  
    }  
}

🧪 Example with a Request and Template

For a contact form submission:

php
Route::post('/contact', 'ContactController@submit');

Controller:

php
use Boshnik\PageBlocks\Http\Request;  

class ContactController extends Controller  
{  
    public function submit(Request $request)  
    {  
        $data = $request->validate([  
            'name' => 'required',  
            'email' => 'required|email',  
        ]);  

        // Save or send an email...  

        return view('contact-success', ['name' => $data['name']]);  
    }  
}

📁 Where Controllers Are Stored

By default, controllers are located in:

html
App\Http\Controllers

If you create an AboutController, its path will be:

html
/core/App/Http/Controllers/AboutController.php

PageBlocks supports several ways to connect controllers:

🧾 Via the Controller@method String

php
Route::get('/about', 'AboutController@index');

PageBlocks automatically adds the namespace App\Http\Controllers.

🧾 Via an Array [Class::class, 'method']

php
use PageBlocks\App\Http\Controllers\AboutController;  

Route::get('/about', [AboutController::class, 'index']);

Useful for IDE autocompletion.

🧾 Class Only – __invoke Method

If you connect a controller without specifying a method, it must contain __invoke():

php
class ContactPageController extends Controller  
{  
    public function __invoke()  
    {  
        return view('contact');  
    }  
}
php
Route::get('/contact', ContactPageController::class);

Great for single-action pages: "Contacts," "Home," "Thank You."

📥 Dependency Injection

Controllers (and anonymous route functions) can automatically receive dependencies. PageBlocks passes:

  • The Request object,
  • Route parameters ({id}, {slug}, etc.).

📨 Injecting the Request Object

php
use Boshnik\PageBlocks\Http\Request;  

class ContactController extends Controller  
{  
    public function submit(Request $request)  
    {  
        $name = $request->input('name');  

        return response("Hello, $name!");  
    }  
}

💡 Works in anonymous functions too:

php
Route::post('/contact', function (Request $request) {  
    return response($request->input('name'));  
});

🧩 Injecting URL Variables

If a route contains variables (e.g., /user/{id}), they are passed to the controller method:

php
Route::get('/user/{id}', 'UserController@show');
php
class UserController extends Controller  
{  
    public function show(Request $request, $id)  
    {  
        return response("User ID: $id");  
    }  
}

🔁 Combined Example

php
Route::get('/order/{id}', 'OrderController@status');
php
class OrderController extends Controller  
{  
    public function status(Request $request, $id)  
    {  
        $userAgent = $request->header('User-Agent');  

        return response("Order #$id. Device: $userAgent");  
    }  
}

© PageBlocks 2019-present