0
0
Laravelframework~5 mins

Why routing maps URLs to logic in Laravel

Choose your learning style9 modes available
Introduction

Routing connects website addresses (URLs) to the code that runs when you visit them. It helps the app know what to do for each URL.

When you want different pages or actions for different website addresses.
When you need to show a user profile page based on their ID in the URL.
When you want to handle form submissions at a specific URL.
When you want to organize your app so each URL triggers specific code.
When you want to create clean and readable URLs for your website.
Syntax
Laravel
Route::get('/url', function () {
    // logic to run
});
Use Route::get for URLs accessed with a browser (GET requests).
The first argument is the URL path, the second is the code to run.
Examples
This runs code to show 'Welcome page' when visiting the home URL.
Laravel
Route::get('/', function () {
    return 'Welcome page';
});
This captures the user ID from the URL and shows it.
Laravel
Route::get('/user/{id}', function ($id) {
    return "User ID: $id";
});
This runs code when a form sends data to '/submit' using POST.
Laravel
Route::post('/submit', function () {
    // handle form submission
});
Sample Program

This example shows three routes: home, about, and a user profile with an ID. Each URL runs different code to show a message.

Laravel
<?php
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return 'Home page';
});

Route::get('/about', function () {
    return 'About us page';
});

Route::get('/user/{id}', function ($id) {
    return "User profile for user $id";
});
OutputSuccess
Important Notes

Routes should be defined in the routes/web.php file in Laravel.

Use curly braces {} to capture parts of the URL as variables.

Routing helps keep your app organized and easy to understand.

Summary

Routing links URLs to the code that runs for them.

It lets you create different pages and actions for different URLs.

Laravel uses simple syntax to define routes with Route::get or Route::post.