Route::get('/', function () {
return 'Hello World';
});
Route::post('foo/bar', function () {
return 'Hello World';
});
Route::put('foo/bar', function () {
//
});
Route::delete('foo/bar', function () {
//
});
示例
app/Http/routes.php
<?php
Route::get('/', function () {
return view('welcome');
});
resources/view/welcome.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel - xuhuhu.com</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;
'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</div>
</div>
</div>
</body>
</html>

-
步骤1 − 首先,我们需要执行应用程序的根URL。
-
步骤2 − 执行URL将匹配 route.php 文件中适当的方法。在我们的示例中,将匹配得到方法和根(“/”)的URL。这将执行相关的函数。
-
步骤3 − 该函数调用模板文件resources/views/welcome.blade.php. 该函数之后使用参数“welcome” 调用 view( )函数而不带blade.php。这将产生以下HTML输出。
路由参数
通常在应用程序中,我们都会捕捉 URL 中传递的参数。要做到这一点,我们需要相应地修改 routes.php 文件文件中的代码。有两种方式,使我们可以捕捉 URL 中传递的参数。
-
必需的参数
-
可选的参数
必需的参数
这些参数必须存在于 URL 中。例如,您可能要从URL中捕获ID用来做与该ID相关的事情。下面是 routes.php 文件的示例编码。
Route::get('ID/{id}',function($id){
echo 'ID: '.$id;
});
我们传递参数在根URL后面 (http://localhost:8000/ID/5),它将被存储在$id变量中,我们可以使用这个参数做进一步处理,但在这里只是简单地显示它。我们可以把它传给视图或控制器进行进一步的处理。
可选参数
有一些参数可能或可能不存在于该URL,这种情况时可使用可选参数。这些参数的存在于URL中不是必需的。这些参数是由“?”符号之后标明参数的名称。下面是 routes.php 文件的示例编码。
Route::get('/user/{name?}',function($name = 'Virat'){
echo "Name: ".$name;
});
示例
routes.php
<?php
// First Route method – Root URL will match this method
Route::get('/', function () {
return view('welcome');
});
// Second Route method – Root URL with ID will match this method
Route::get('id/{id}',function($id){
echo 'The value of ID is: '.$id;
});
// Third Route method – Root URL with or without name will match this method
Route::get('/user/{name?}',function($name = 'Virat Gandhi'){
echo "The value of Name is: ".$name;
});
第1步 - 在这里,我们定义了3个路由使用get方法用于不同的目的。如果我们执行下面的网址则它将执行第一个方法。
http://localhost:8000

第3步 −如果我们执行下面的网址,将执行第二个方法,崦参数/参数ID将被传递到变量$id。
http://localhost:8000/id/365
第4步 − URL成功执行后,会收到以下输出 -
第5步 − 如果执行下面的网址将执行第三个方法,可选参数/参数名称将传递给变量$name。最后一个参数 'Virat“ 是可选的。如果你删除它,默认的名称将被使用,我们的函数传递 “zaixian” 参数值。
http://localhost:8000/user/zaixian
第6步 − URL成功执行后,您会收到以下输出-
