📘 Laravel Controller
Controllers in Laravel help organize logic by grouping request handling into a single class following the MVC (Model-View-Controller) design pattern.
✅ What is a Controller?
A controller is a PHP class in app/Http/Controllers
that handles HTTP requests and returns responses.
🛠️ Creating a Controller
php artisan make:controller SampleController
This creates: app/Http/Controllers/SampleController.php
📄 Basic Structure
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SampleController extends Controller { public function index() { return view('welcome'); } }
📌 Types of Controllers
- Basic Controller – Simple class with methods
- Resource Controller – Full CRUD controller
- Invokable Controller – One-method controller
php artisan make:controller ProductController --resource
php artisan make:controller SingleActionController --invokable
🔄 Mapping Controller to Routes
In routes/web.php
:
use App\Http\Controllers\SampleController; Route::get('/sample', [SampleController::class, 'index']);
Resource Route:
Route::resource('products', ProductController::class);
📥 Passing Data to Views
public function index() { $name = "John"; return view('home', ['name' => $name]); }
In Blade View:
<h1>Hello, {{ '{{ $name }}' }}</h1>
🧪 Example: Full CRUD Controller
class ProductController extends Controller { public function index() { // Show all products } public function create() { // Show create form } public function store(Request $request) { // Save new product } public function show($id) { // Show one product } public function edit($id) { // Show edit form } public function update(Request $request, $id) { // Update product } public function destroy($id) { // Delete product } }
🧰 Dependency Injection
public function store(Request $request) { return $request->all(); }
📘 Summary Table
Feature | Command/Syntax |
---|---|
Create Controller | php artisan make:controller |
Resource Controller | --resource |
Invokable Controller | --invokable |
Routing | Route::get() / Route::resource() |
Return View | return view('name') |
Inject Request | function(Request $req) |
0 Comments