Controllers
Make a controller
Controllers are classes that group the logic of related pages. Artisan generates one with the correct namespace and base class.
Generate a post controller
php artisan make:controller PostController
INFO Controller [app/Http/Controllers/PostController.php] created successfully.
The file appears in app/Http/Controllers. Open it and you will see an empty class ready for methods.
Controller methods
Each public method handles one page or action. The controller below shows a post list and a single post page.
namespace App\Http\Controllers; class PostController extends Controller { public function index() { return view("posts.index"); } public function show(string $id) { return view("posts.show", ["id" => $id]); } }
Routes point at methods with a class and method pair. The framework creates the controller and calls the method for you.
use App\Http\Controllers\PostController; use Illuminate\Support\Facades\Route; Route::get("/posts", [PostController::class, "index"]);
Single-action controllers
A controller with exactly one job uses the invoke method instead of a named method. The class stays small and its purpose is obvious.
namespace App\Http\Controllers; class ShowPost extends Controller { public function __invoke(string $id) { return view("posts.show", ["id" => $id]); } }
The route names only the class, with no method in an array. Laravel calls the invoke method automatically.
use App\Http\Controllers\ShowPost; use Illuminate\Support\Facades\Route; Route::get("/posts/{id}", ShowPost::class);
Read the request
Type the Request class in a method signature and Laravel hands you the current request. The input method reads one form or query value by name.
Always validate input before saving it to a database. The store method below only reads and echoes for now.
namespace App\Http\Controllers; use Illuminate\Http\Request; class PostController extends Controller { public function store(Request $request) { $title = $request->input("title"); return response()->json(["title" => $title]); } }
Next: Blade basics
Article author: Arthur Isaev