Laravel Series · Chapter 2 · Routing

Laravel Routing
Complete Guide in Hindi

Laravel Routing की पूरी जानकारी — Basic Routes, Route Parameters, Named Routes, Route Groups, Middleware, Resource Routes, Route Model Binding। Real examples के साथ।

🌐 Basic Routes 🔢 Parameters 🏷️ Named Routes 📦 Groups 🔁 Resource Routes
routes/web.php · api.php · console.php
Route::get post put patch delete
{param}Route parameter syntax
->name()Named route method

📋 इस Article में क्या-क्या है

  1. Routing क्या है?
  2. HTTP Methods — GET, POST, PUT, DELETE
  3. Route Parameters
  4. Optional Parameters
  5. Route Constraints — Regex
  6. Named Routes
  7. Route Groups
  8. Middleware in Routes
  9. Resource Routes
  10. Route Model Binding
1
Routing क्या है?

Routing — URL requests को सही controller/function तक पहुँचाने का process। User /products visit करे तो products show हों, /login visit करे तो login form — यही routing करता है।

Browser Request
/products
routes/web.php
Route Match
Middleware
Check
Controller
Method
Response
HTML/JSON
ROUTE FILES — कहाँ रखते हैं?
routes/web.php ← Browser routes (session, CSRF)
routes/api.php ← API routes (/api/... prefix, stateless)
routes/console.php← Artisan command routes

// web.php — यही सबसे ज़्यादा use होता है
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

Route::get("/", function() {
  return view("welcome");
});
?>

2
HTTP Methods — GET, POST, PUT, DELETE
ALL HTTP METHODS
<?php
// GET — Data पढ़ना, page show करना
Route::get("/products", function() {
  return "All products";
});

// POST — Data create करना (form submit)
Route::post("/products", function() {
  return "Create product";
});

// PUT — Data पूरा update करना
Route::put("/products/{id}", function(int $id) {
  return "Update product $id";
});

// PATCH — Data partially update करना
Route::patch("/products/{id}", function(int $id) {
  return "Patch product $id";
});

// DELETE — Data delete करना
Route::delete("/products/{id}", function(int $id) {
  return "Delete product $id";
});

// Multiple methods एक route पर
Route::match(["get", "post"], "/contact", function() {
  return "Contact page";
});

// कोई भी method accept करो
Route::any("/webhook", function() {
  return "Webhook received";
});
?>
MethodUse CaseCRUD
GETData read करना, page showRead
POSTNew data create करनाCreate
PUTपूरा record updateUpdate
PATCHPartial updateUpdate
DELETERecord delete करनाDelete
CONTROLLER को POINT करना — Preferred Way
<?php
use App\Http\Controllers\ProductController;

// Closure की जगह Controller use करो
Route::get("/products", [ProductController::class, "index"]);
Route::get("/products/{id}", [ProductController::class, "show"]);
Route::post("/products", [ProductController::class, "store"]);
Route::put("/products/{id}", [ProductController::class, "update"]);
Route::delete("/products/{id}",[ProductController::class, "destroy"]);
?>

3
Route Parameters — URL से Data लेना
{id}
param

Route Parameters

URL के अंदर dynamic values — {id}, {slug}, {username}। Curly braces {} में wrap करो — Laravel automatically function में pass करता है।

{param} — required {param?} — optional Type hints support
ROUTE PARAMETERS — EXAMPLES
<?php
// Single parameter
Route::get("/users/{id}", function(int $id) {
  return "User ID: $id";
});
// /users/42 → "User ID: 42"

// Multiple parameters
Route::get("/users/{userId}/posts/{postId}", function(int $userId, int $postId) {
  return "User $userId का Post $postId";
});
// /users/1/posts/5 → "User 1 का Post 5"

// String parameter — slug
Route::get("/blog/{slug}", function(string $slug) {
  return "Blog post: $slug";
});
// /blog/laravel-tutorial → "Blog post: laravel-tutorial"
?>

4
Optional Parameters — {param?}
OPTIONAL PARAMETERS — ? SUFFIX
<?php
// {page?} — optional, ? लगाओ + default value दो
Route::get("/products/{category?}", function(string $category = "all") {
  return "Category: $category";
});
// /products → "Category: all"
// /products/mobile → "Category: mobile"

// Pagination example
Route::get("/blog/{page?}", function(int $page = 1) {
  return "Blog page: $page";
});
// /blog → "Blog page: 1"
// /blog/3 → "Blog page: 3"
?>

5
Route Constraints — Regex Validation
WHERE CONSTRAINTS — Parameter Validate करो
<?php
// Numeric only
Route::get("/users/{id}", function(int $id) {
  return "User $id";
})->where("id", "[0-9]+"); // /users/abc → 404

// Alpha only
Route::get("/users/{name}", function(string $name) {
  return "User $name";
})->where("name", "[a-zA-Z]+");

// Multiple constraints
Route::get("/posts/{id}/{slug}", function(int $id, string $slug) {
  return "Post $id: $slug";
})->where([
  "id" => "[0-9]+",
  "slug" => "[a-z0-9-]+",
]);

// Helper constraints — shorthand
Route::get("/users/{id}", function(int $id) {})->whereNumber("id");
Route::get("/posts/{slug}", function(string $slug) {})->whereAlphaNumeric("slug");
Route::get("/users/{uuid}", function(string $uuid) {})->whereUuid("uuid");
?>

6
Named Routes — Routes को नाम देना
🏷️
name

Named Routes

Routes को name देने से URL hardcode करने की ज़रूरत नहीं। URL बदलने पर सिर्फ route file update करो — बाकी code automatically update।

->name() route() helper URL changes safe

❌ URL Hardcode — Bad

// URL change होने पर सब जगह change
<a href="/products/{{ $product->id }}">
  View Product
</a>

✅ Named Route — Good

// route() helper — URL auto generate
<a href="{{ route('products.show', $product) }}">
  View Product
</a>
NAMED ROUTES — DEFINE & USE
<?php
// Route को name दो — ->name()
Route::get("/products", [ProductController::class, "index"])->name("products.index");
Route::get("/products/{id}", [ProductController::class, "show"])->name("products.show");
Route::get("/products/create", [ProductController::class, "create"])->name("products.create");
Route::post("/products", [ProductController::class, "store"])->name("products.store");

// PHP में use करना
// Simple URL
$url = route("products.index"); // /products
// Parameter के साथ
$url = route("products.show", ["id" => 42]); // /products/42
// Short form
$url = route("products.show", 42); // /products/42

// Redirect करना
return redirect()->route("products.index");
return to_route("products.show", $product); // Laravel 9+

// Current route check
if (request()->routeIs("products.*")) {
  // Products routes पर हैं
}
?>

7
Route Groups — Routes को Group करना

Related routes को group में रखो — common prefix, middleware, namespace share करते हैं। Code DRY रहता है।

ROUTE GROUPS — PREFIX, MIDDLEWARE, NAME
<?php
// Prefix — /admin/... सब routes
Route::prefix("admin")->group(function() {
  Route::get("/dashboard", [AdminController::class, "dashboard"]); // /admin/dashboard
  Route::get("/users", [AdminController::class, "users"]); // /admin/users
  Route::get("/settings", [AdminController::class, "settings"]); // /admin/settings
});

// Middleware group
Route::middleware(["auth", "verified"])->group(function() {
  Route::get("/dashboard", [DashboardController::class, "index"]);
  Route::get("/profile", [ProfileController::class, "show"]);
  Route::get("/orders", [OrderController::class, "index"]);
});

// Name prefix
Route::name("admin.")->group(function() {
  Route::get("/admin/dashboard", [AdminController::class, "index"])->name("dashboard");
  // route("admin.dashboard") से access
});

// Chained — prefix + middleware + name एक साथ
Route::prefix("admin")
    ->middleware(["auth", "admin"])
    ->name("admin.")
    ->group(function() {
      Route::get("/dashboard", [AdminController::class, "index"])->name("dashboard");
      Route::get("/users", [UserController::class, "index"])->name("users");
    // route("admin.dashboard") → /admin/dashboard
    // route("admin.users") → /admin/users
    });
?>

8
Middleware in Routes — Access Control
Middleware — Request को Controller तक पहुँचने से पहले filter करता है। Authentication check, logging, CORS — सब middleware से।
MIDDLEWARE — COMMON EXAMPLES
<?php
// auth — Login check
Route::get("/dashboard", [DashboardController::class, "index"])
     ->middleware("auth");

// Multiple middleware
Route::get("/admin", [AdminController::class, "index"])
     ->middleware(["auth", "verified", "admin"]);

// Guest only — login page (already logged in तो redirect)
Route::get("/login", [AuthController::class, "showLogin"])->middleware("guest");
Route::get("/register", [AuthController::class, "showRegister"])->middleware("guest");

// Rate limiting
Route::post("/api/data", [ApiController::class, "store"])
     ->middleware("throttle:60,1"); // 60 req/minute

// Common Built-in Middleware:
// auth — Authenticated user
// auth:sanctum — API token auth
// guest — Non-authenticated
// verified — Email verified
// throttle:n,m — Rate limit n requests per m minutes
// signed — Signed URL
// can:permission— Authorization
?>

9
Resource Routes — CRUD एक Line में
📦
rsrc

Route::resource()

CRUD के लिए 7 routes एक line में। Laravel automatically index, create, store, show, edit, update, destroy — सब routes बनाता है।

7 routes in 1 line RESTful convention Named automatically
RESOURCE ROUTE — DEFINE
<?php
// यह एक line = 7 routes!
Route::resource("products", ProductController::class);

// Specific routes only
Route::resource("products", ProductController::class)->only(["index", "show"]);
Route::resource("products", ProductController::class)->except(["destroy"]);

// API resource — no create/edit (no HTML forms)
Route::apiResource("products", ProductController::class);

// Multiple resources
Route::resources([
  "products" => ProductController::class,
  "orders" => OrderController::class,
  "users" => UserController::class,
]);
?>
MethodURIActionRoute Name
GET/productsindex()products.index
GET/products/createcreate()products.create
POST/productsstore()products.store
GET/products/{id}show()products.show
GET/products/{id}/editedit()products.edit
PUT/PATCH/products/{id}update()products.update
DELETE/products/{id}destroy()products.destroy
💡 php artisan route:list: सब active routes देखने के लिए। php artisan route:list --path=products से specific routes filter करो।

10
Route Model Binding — Auto DB Fetch
🔗
bind

Route Model Binding

URL से {id} मिला — DB से automatically Model fetch। Manual Product::findOrFail($id) लिखने की ज़रूरत नहीं। Laravel खुद 404 handle करता है।

Auto DB fetch 404 auto handle Type hint magic

❌ Without Binding — Manual

Route::get("/products/{id}", function(int $id) {
  $product = Product::findOrFail($id);
  return $product->name;
});

✅ With Binding — Auto Magic

Route::get("/products/{product}", function(Product $product) {
  // $product already fetched from DB!
  return $product->name;
});
ROUTE MODEL BINDING — COMPLETE EXAMPLES
<?php
use App\Models\Product;

// Implicit Binding — type hint लगाओ, Laravel fetch करेगा
Route::get("/products/{product}", function(Product $product) {
  return $product; // JSON response
}); // /products/42 → Product id=42 fetch, 404 अगर नहीं मिला

// Controller में भी same
Route::get("/products/{product}", [ProductController::class, "show"]);
// Controller method:
// public function show(Product $product) { return $product; }

// Slug से bind करना — id की जगह slug
Route::get("/blog/{post:slug}", function(Post $post) {
  return $post;
}); // /blog/laravel-tutorial → slug='laravel-tutorial' से fetch

// Model में getRouteKeyName() define करके
// class Post extends Model {
// public function getRouteKeyName() { return "slug"; }
// }
?>
Pattern: Route::resource() + Route Model Binding = Clean, minimal code। Manual findOrFail() और 404 handling की ज़रूरत नहीं।

Quick Reference — Routing Cheatsheet
Syntaxकाम
Route::get('/path', fn)GET route define
Route::post('/path', fn)POST route define
Route::resource('products', Ctrl)7 CRUD routes एक line में
Route::apiResource('products', Ctrl)API CRUD (5 routes, no HTML forms)
{id}Required parameter
{id?}Optional parameter
->where('id', '[0-9]+')Parameter constraint
->whereNumber('id')Numeric constraint shorthand
->name('products.index')Route को name देना
route('products.index')Named route URL generate
->middleware('auth')Middleware attach करना
Route::prefix('admin')URL prefix group
Route::middleware(['auth'])Middleware group
Route::name('admin.')Name prefix group
Product $product (type hint)Route Model Binding
{post:slug}Custom column binding
php artisan route:listAll routes show करो

निष्कर्ष

Laravel Routing powerful और clean है। Resource routes से CRUD एक line में, Named routes से URL management easy, Route Model Binding से boilerplate खत्म।

routes/web.php — सब browser routes यहाँ। API routes → routes/api.php।

Route::resource() — CRUD के लिए always। 7 routes एक line में।

Named Routes — हमेशा name दो। URL change होने पर sirf route file update।

Route Groups — prefix + middleware + name एक साथ। DRY code।

Route Model Binding — Type hint करो — Laravel DB से fetch करेगा।

🚀 अगला Chapter: Chapter 3: Laravel Controllers — Resource Controllers, Invokable Controllers, Dependency Injection, Form Requests।