laravel 路由

来源:互联网 发布:js获取鼠标点击位置 编辑:程序博客网 时间:2024/06/04 19:17

基本路由 支持HTTP Method 或者正则匹配等,还有就是自定义

支持的Method有:get,post,put,patch,options,delete

Route::get('xxx',xxx);Route::get('xxx/*',xxx);Route::post('xxx',function(){ xxxx });Route::get('/', 'DashBoardController@index');


匹配路由: match, any

ep:

Route::get('user', 'UserController@index');这里是你访问xxx/user 的时候会调用 UserController中的index 方法

在laravel 5 .0 以后 必须把包名放进去 

Route::get('user', 'User\UserController@index');

1.首先最基础的路由

   

Route::get('/',function(){    return 'hello world';});
代码解释:
get方式跳转到/(本地通常为localhost/) 然后调用function,输出‘hello world’


Route::post('/',function(){    return 'hello world';});


2.路由绑定控制器

绑定控制器的作用:实现mvc模式的开发

Route::get('user', ‘userController@index()’);<span style="font-size:14px;">代码解释:</span>同理跳转<code>user</code>然后调用<code>Controller</code>文件夹下的<code>userController</code>类中的<code>index</code>方法<p>3.路由使用参数</p><p><pre name="code" class="php">Route::get('user/{name}','userController@index()');代码解释:同理此处跳转<code>user/{name}</code>,而<code>{name}</code>的值来自于<code>get</code>得到的参数,比如查看谋个用户时通过<code>user/{name}</code>来获取用户比<code>user/xxxx</code>这种方式来的更为方便

4.路由使用默认参数

当然我们有时候需要设置默认值,可以通过以下方式来设置

Route::get('user/{name?}', function($name = null){    return $name;});

5.路由使用正则表达式限定参数

限定参数的作用:具体待续

Route::get('user/{name}', function($name){//})->where('name', '[A-Za-z]+');Route::get('user/{id}', function($id){    //})->where('id', '[0-9]+');
代码解释:
同理此处的{name}也是一个参数,二后面的where('','')则是限定条件


6.录用使用数组来限定多个参数

Route::get('user/{id}/{name}', function($id, $name){    //})->where(array('id' => '[0-9]+', 'name' => '[a-z]+'))<p>7.定义全局模式</p><p>如果希望在全局范围用指定正则表达式限定路由参数,可以使用 pattern 方法:</p><p><pre name="code" class="php">Route::pattern('id', '[0-9]+');Route::get('user/{id}', function($id){// Only called if {id} is numeric.});

8.访问路由参数

Route::filter('foo', function(){    if (Route::input('id') == 1){        echo "hello";    }});代码解释:此处<code>‘foo’</code>过滤器将会访问<code>调用此过滤器</code>的参数<code>id</code>如果<code>id==1</code>则输出"hello";<span style="font-size:14px;"></span><pre name="code" class="php"><pre name="code" class="php"><pre class="hljs php"><code></code><p name="code" class="php"><h5>定义过滤器</h5></p><p><pre name="code" class="php">Route::filter('old', function(){    if (Input::get('age') < 200){    return Redirect::to('home');}});
代码解释:过滤器名字为old,执行function(),如果得到的age<200那么重定位到home


为路由绑定使用过滤器
过滤器的作用:限制对应用程序中某些功能访问,比如对于需要验证才能访问的功能就非常有用
Route::get('admin/home',        ['as'=>'admin.home','before'=>'adminFilter',function(){    echo "hello world"}])

代码解释:此处跳转admin\home,其中'as'=>'admin.home'是别名。然后在跳转之前会先运行名为adminFilter的过滤器,如果过滤器没有阻止该路由则运行function,否则就不会运行function(),过滤器定义在filters.php文件中,位于routes.php下面。














 




0 0