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 - h3.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“ 是可选的。如果你删除它,默认的名称将被使用,我们的函数传递 “h3” 参数值。
http://localhost:8000/user/h3
第6步 − url成功执行后,您会收到以下输出-