在Laravel中,所有请求都在路由的帮助下进行映射.基本路由将请求路由到关联的控制器.本章讨论Laravel中的路由.
Laravel中的路由包括以下类别 :
基本路由
路由参数
命名路由
所有申请路线都在 app/routes.php 文件中注册.该文件告诉Laravel它应该响应的URI,并且相关的控制器将给它一个特定的调用.欢迎页面的示例路线可以看作如下面给出的屏幕截图所示 :
Route::get ('/', function () { return view('welcome');});
观察以下示例以了解有关路由的更多信息;
app/Http/routes.php
<?php Route::get('/', function () { return view('welcome'); });
resources/view/welcome.blade.php
<!DOCTYPE html> <html> <head> <title>Laravel</title> <link href = "https://fonts.googleapis.com/css?family=Lato:100" rel = "stylesheet" type = "text/css"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; display: table; font-weight: 100; font-family: 'Lato'; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; } </style> </head> <body> <div class = "container"> <div class = "content"> <div class = "title">Laravel 5.1</div> </div> </div> </body> </html>
路由机制如下图所示 :
现在让我们详细了解路由机制中涉及的步骤 :
步骤1 : 最初,我们应该执行应用程序的根URL.
第2步 : 现在,执行的URL应该与 route.php 文件中的相应方法匹配.在本例中,它应该与方法和根('/')URL匹配.这将执行相关功能.
步骤3 : 该函数调用模板文件 resources/views/welcome.blade.php.接下来,该函数使用参数'welcome'调用 view()函数. b>不使用 blade.php .
这将产生HTML输出,如下图所示 :
有时在网络应用程序中,你可能需要捕获通过URL传递的参数.为此,您应该修改 routes.php 文件中的代码.
您可以捕获 routes.php 文件中的参数这里讨论的两种方式 :
这些参数是为了路由Web应用程序而应强制捕获的参数.例如,从URL捕获用户的标识号很重要.这可以通过定义路线参数来实现,如下所示 :
Route::get('ID/{id}',function($id) { echo 'ID: '.$id; });
有时开发人员可以生成参数作为可选参数,并且可以包含? 在URL中的参数名称之后.保持提到的默认值作为参数名称很重要.请看下面的示例,其中显示了如何定义可选参数 :
Route::get('user/{name?}', function ($name = 'TutorialsPoint') { return $name;});
上面的示例检查该值是否与 TutorialsPoint 匹配,并相应地路由到定义的URL.
命名路由允许以方便的方式创建路由.可以使用name方法在路由定义上指定路由的链接.以下代码显示了使用controller创建命名路由的示例;
Route::get('user/profile', 'UserController@showProfile')->name('profile');
用户控制器将调用函数 showProfile ,参数为 profile .参数使用 name 方法到路径定义上.