Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Controllers

While there are few routes, the code can live right in routes/web.php. But as the project grows, that file swells. A controller is a class that groups the request handlers for one part of the site, for example for posts.

Creating a controller

A controller is created with an Artisan command:

php artisan make:controller PostController

The file appears at app/Http/Controllers/PostController.php.

A controller method

Each method handles one request and returns a response:

namespace App\Http\Controllers;
 
class PostController extends Controller
{
    public function index()
    {
        return 'List of posts';
    }
}

Binding to a route

The route names the class and the method:

use App\Http\Controllers\PostController;
 
Route::get('/posts', [PostController::class, 'index']);

Route parameters

A parameter from the address arrives as a method argument:

public function show(string $id)
{
    return "Post $id";
}
Route::get('/posts/{id}', [PostController::class, 'show']);

Request data

To read form data or the query string, add a Request object to the arguments — Laravel injects it for you:

use Illuminate\Http\Request;
 
public function search(Request $request)
{
    $query = $request->input('q', '');
 
    return "Searching for: $query";
}

The second argument of input() is the default value when the parameter is missing.

Resource controllers

For the typical set of actions — list, view, create, update, delete — there is a ready-made template:

php artisan make:controller PostController --resource

All seven routes are registered with one line:

Route::resource('posts', PostController::class);
Method and addressController method
GET /postsindex
GET /posts/createcreate
POST /postsstore
GET /posts/{post}show
GET /posts/{post}/editedit
PUT /posts/{post}update
DELETE /posts/{post}destroy

Common mistake

If you forget the use line for the controller in the routes file, Laravel cannot find the class and fails with Target class [PostController] does not exist. Check that use App\Http\Controllers\PostController; is at the top of routes/web.php.

Thanks for reading!

Donate to the site — we work hard for you.