What is a controller in Laravel? How do you create one?
In Laravel, a controller is a class that handles HTTP requests and contains the logic for processing them. Controllers are a key part of the MVC (Model-View-Controller) architecture in Laravel, which helps in organizing your application’s code by separating the concerns of request handling, business logic, and presentation.
Creating a Controller
To create a controller in Laravel, you can use the Artisan command-line tool. Here’s how you can create a controller:
-
Using Artisan Command
Open your terminal and navigate to your Laravel project directory. Run the following command:
php artisan make:controller MyController
This command will create a new controller file named
MyController.php
in theapp/Http/Controllers
directory. -
Controller Code Example
Once created, you can open the
MyController.php
file. Here’s an example of a basic controller with a few methods:<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class MyController extends Controller { public function index() { return view('welcome'); // Returns a view named 'welcome' } public function show($id) { // Fetch a model or resource based on $id and return a view $data = Model::find($id); return view('show', ['data' => $data]); } public function store(Request $request) { // Handle form submission or data processing $validated = $request->validate([ 'name' => 'required|max:255', ]); Model::create($validated); return redirect()->route('home'); } }
index
Method: Returns a view namedwelcome
.show
Method: Fetches a model or resource by ID and returns a view with the data.store
Method: Validates and processes data from a request, then redirects to a named route.
-
Routing to Controller
To use this controller, you need to define routes in the
routes/web.php
file:use App\Http\Controllers\MyController; Route::get('/', [MyController::class, 'index']); Route::get('/show/{id}', [MyController::class, 'show']); Route::post('/store', [MyController::class, 'store']);
- The
/
route calls theindex
method ofMyController
. - The
/show/{id}
route calls theshow
method with an ID parameter. - The
/store
route calls thestore
method when a POST request is made.
- The
Summary
Controllers in Laravel help to handle HTTP requests and organize your application's logic. You can create a controller using the php artisan make:controller
command, define methods for different types of requests, and route to these methods from your routes file.
If you need more specific examples or have any other questions about controllers, feel free to ask!
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.