Laravel 路由通过 routes/web.php 和 routes/api.php 定义,支持基础 HTTP 方法路由、资源路由、参数约束、命名与分组、模型绑定等特性,是应用入口枢纽,需注重命名一致性、中间件顺序和参数安全。

在 Laravel 中定义路由非常直观,主要通过 routes/ 目录下的文件完成,最常用的是 routes/web.php(处理 Web 请求)和 routes/api.php(处理 API 请求)。
使用 Route:: 门面配合 HTTP 方法方法注册路由:
Route::get('/home', [HomeController::class, 'index']); —— GET 请求Route::post('/user', [UserController::class, 'store']); —— POST 请求Route::put('/user/{id}', [UserController::class, 'update']); —— 带参数的 PUT 路由Route::resource('posts', PostController::class); —— 快速注册 RESTful 资源路由支持必填、可选参数及正则约束,增强灵活性和安全性:
Route::get('/user/{id}', ...)
Route::get('/user/{id?}', ...),需在闭包或控制器中提供默认值->where('id', '[0-9]+'),防止非法 ID 访问->where(['id' => '[0-9]+', 'slug' => '[a-z\-]+'])
命名便于在视图或代码中生成 URL;分组用于统一前缀、中间件、域名等:
由最初的武安热线、海南供求修正而来,套用520界面,美观无错升级说明:1、增加首页调用文件,调用文件是listinfo.asp调用代码: num为显示信息数,修改listinfo.asp文件可以定义标题字数等。2、增加分类别搜索功能。3、增加首页图片广告功能。4、增加首页连接功能。5、对后台进行重新编写。6、修正了v1.0已知的全部bug管理路径:/amin/管理密码:admin
0
立即学习“PHP免费学习笔记(深入)”;
Route::get('/profile', ...)->name('profile');,调用时用 route('profile')
Route::prefix('admin')->group(function () { ... });
Route::middleware(['auth'])->group(function () { ... });
Route::domain('{account}.example.com')->group(...)
自动注入模型实例,避免手动查询:
Route::get('/posts/{post}', [PostController::class, 'show']);,Laravel 自动按主键查找 Post 模型RouteServiceProvider::boot() 中注册 Route::model('post', Post::class);
Route::bind('post', function ($value) { return Post::where('slug', $value)->firstOrFail(); });
基本上就这些。路由是 Laravel 应用的入口枢纽,合理组织能大幅提升可维护性。不复杂但容易忽略细节,比如命名一致性、中间件顺序、参数约束是否到位。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号