Laravel Routing
Complete Guide in Hindi
Laravel Routing की पूरी जानकारी — Basic Routes, Route Parameters, Named Routes, Route Groups, Middleware, Resource Routes, Route Model Binding। Real examples के साथ।
📋 इस Article में क्या-क्या है
- Routing क्या है?
- HTTP Methods — GET, POST, PUT, DELETE
- Route Parameters
- Optional Parameters
- Route Constraints — Regex
- Named Routes
- Route Groups
- Middleware in Routes
- Resource Routes
- Route Model Binding
Routing — URL requests को सही controller/function तक पहुँचाने का process। User /products visit करे तो products show हों, /login visit करे तो login form — यही routing करता है।
/products
Route Match
Check
Method
HTML/JSON
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");
});
?>
// 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";
});
?>
| Method | Use Case | CRUD |
|---|---|---|
| GET | Data read करना, page show | Read |
| POST | New data create करना | Create |
| PUT | पूरा record update | Update |
| PATCH | Partial update | Update |
| DELETE | Record delete करना | Delete |
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"]);
?>
// 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"
?>
// {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"
?>
// 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");
?>
❌ URL Hardcode — Bad
<a href="/products/{{ $product->id }}">
View Product
</a>
✅ Named Route — Good
<a href="{{ route('products.show', $product) }}">
View Product
</a>
// 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 पर हैं
}
?>
Related routes को group में रखो — common prefix, middleware, namespace share करते हैं। Code DRY रहता है।
// 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
});
?>
// 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
?>
// यह एक 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,
]);
?>
| Method | URI | Action | Route Name |
|---|---|---|---|
| GET | /products | index() | products.index |
| GET | /products/create | create() | products.create |
| POST | /products | store() | products.store |
| GET | /products/{id} | show() | products.show |
| GET | /products/{id}/edit | edit() | products.edit |
| PUT/PATCH | /products/{id} | update() | products.update |
| DELETE | /products/{id} | destroy() | products.destroy |
❌ Without Binding — Manual
$product = Product::findOrFail($id);
return $product->name;
});
✅ With Binding — Auto Magic
// $product already fetched from DB!
return $product->name;
});
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"; }
// }
?>
| 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:list | All 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 करेगा।