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成功執行後,您會收到以下輸出-
