Ad Code

Responsive Advertisement

🐱‍👤 Laravel - Routing

📘 Laravel Routing 


Routing in Laravel allows you to define URLs and link them to specific functionality in your application. All routes are defined in the routes/ directory.

📁 Laravel Routes Directory

File Purpose
web.php Routes for web interfaces (uses session, CSRF protection).
api.php Routes for APIs (stateless).
console.php For Artisan command routes.
channels.php Used for event broadcasting channels.

🧭 Basic Route Syntax

Route::get('/about', function () {
    return view('about');
});
  • get – HTTP method
  • /about – URL path
  • function – Closure that handles the request

🚦 Route Methods

Route::get('/home', ...);
Route::post('/submit', ...);
Route::put('/update', ...);
Route::delete('/delete', ...);
Route::patch('/modify', ...);
Route::options('/check', ...);
  

🎯 Route Parameters

Required Parameters

Route::get('/user/{id}', function ($id) {
    return "User ID: $id";
});

Optional Parameters

Route::get('/post/{id?}', function ($id = null) {
    return $id ? "Post ID: $id" : "No post ID provided";
});

With Regex Constraints

Route::get('/product/{id}', function ($id) {
    return "Product: $id";
})->where('id', '[0-9]+');

📁 Route to Controller

Route::get('/users', [UserController::class, 'index']);

Laravel 8+ syntax using use App\Http\Controllers\UserController;

🔒 Middleware in Routes

Route::get('/dashboard', [DashboardController::class, 'index'])
     ->middleware('auth');

🗂️ Route Groups

Route::prefix('admin')->middleware('auth')->group(function () {
    Route::get('/dashboard', ...);
    Route::get('/users', ...);
});

🏷️ Named Routes

Route::get('/profile', [UserController::class, 'show'])->name('profile');
route('profile'); // Generates URL
  

📥 Route Redirect

Route::redirect('/old', '/new', 301);

🔁 Route View

Route::view('/welcome', 'welcome');

🌐 API Routes (Stateless)

In routes/api.php, routes are automatically prefixed with /api.

Route::get('/users', [UserController::class, 'index']);

🧪 Testing Routes

php artisan route:list

Displays all registered routes with methods, middleware, names, and URIs.

🧠 Summary Table

Concept Syntax Example
Basic Route Route::get('/home', function () {...});
Route with Parameter Route::get('/user/{id}', fn($id) => ...);
Route with Controller Route::get('/posts', [PostController::class, 'index']);
Named Route ->name('route.name')
Middleware ->middleware('auth')
Group Routes Route::group([...], function () {...});
API Route Defined in api.php, prefixed with /api

Post a Comment

0 Comments