Laravel Routing Basics and Advanced Usage

This article explains Laravel's routing system, covering the default route file, basic GET routes, common HTTP methods, parameter constraints, multiple parameters, and how to bind routes to controller actions with practical code examples.

php Courses
php Courses
php Courses
Laravel Routing Basics and Advanced Usage

In web development, routers select paths and forward packets; similarly, framework routing handles HTTP request paths to invoke specific functionality, improving SEO by shortening URLs.

Default Route File

All Laravel routes are defined in the routes directory, automatically loaded by the framework. The primary file is routes/web.php.

use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});

Basic Route

A simple route returning a string:

Route::get('index', function () {
return "study laravel";
});

Visiting localhost:8000/index displays "study laravel".

Common Route Methods

Beyond get, Laravel provides post, put, delete, any (matches all request methods), and match (specifies multiple methods).

Route::match(['get', 'post'], 'list', function () {
return 'list';
});

Parameter Passing

Routes can capture parameters, e.g., /news/1:

Route::get('news/{id}', function ($id) {
return 'news:' . $id;
});

To restrict {id} to digits:

Route::get('news/{id}', function ($id) {
return 'news:' . $id;
})->where('id', '\d+');

Multiple parameters with constraints:

Route::get('/name/{name}/age/{age}', function ($name, $age) {
echo "name:$name age:$age";
})->where(['name' => '\w+', 'age' => '\d+']);

Binding Routes to Controllers

Create a controller app/Http/Controllers/IndexController.php:

<?php
namespace App\Http\Controllers;
class IndexController extends Controller {
public function news($id) {
echo "news:$id";
}
}

Then bind the route:

Route::get('news/{id}', 'IndexController@news')->where('id', '\d+');

Accessing /news/1 now invokes the news method of IndexController.

If the controller resides in a sub‑namespace, e.g., app/Http/Controllers/Home/IndexController.php, set the route as:

Route::get('home', 'Home\IndexController@index');
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendroutingWeb DevelopmentPHPLaravel
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.