7gugu’s blog

日本分站

路由使用笔记v1.0

Laravel路由简介: 路由第一个参数是访问的路径,第二个参数是一个action 比如: 输出视图

[php] Route::any('/',function(){ return view('welcome');//输出模板welcome }); Route::any('/',function(){ return 'Hello World';//单纯的输出文字 }); [/php]

一般路由器不会直接输出视图,只会用来绑定控制器,并且进行传参操作


路由传参

比如: web.php

[php]Route::any('/center/{id}','CenterController@id');[/php]

(注释:把id这个参数传入CenterController这个控制器的id这个方法) app/Http/CenterController.php

[php] namespace App\Http\Controllers;

class CenterController extends Controller{ public function id($id){ return 'Member-ID-'.$id; } } [/php]

(注释:接收来自路由传入变量id)

[php] Route::any('/center/{name?}','CenterController@id');[/php]

(注释:此处变量name后面的"?"的作用是说明该变量具有默认值,即可以在控制器中对应的方法中传参时设定一个默认参数,如果不使用该标识的话会导致访问时出现报错/404页面的出现)


路由参数过滤器

比如: 过滤单个参数

[php]Route::any("/center/{id}",'CenterController@id')->where('id','[0-9]+');[/php]

过滤多个参数

[php]Route::any("/center/{id}/{name}",'CenterController@id')->where(['id'=>'[0-9]+','name'=>'[A-Za-z]+']);[/php]

(注释:where把路由指向where函数即可启用过滤器,过滤器的第一个参数是要过滤的变量名,第二个参数是过滤的正则表达式,如果不遵循正则表达式的话,会先匹配其他路由规则,若无符合的规则,则会抛出404/错误)


Laravel路由类型:

  1. Get路由
  2. Post路由
  3. Any路由
  4. Match路由

下面将开始详解每一个路由的用法(个人总结的笔记)

Get路由

[php] Route::get('/','ControllerName@MethodName'); [/php]

顾名思义通过给服务器发起get请求时,可以触发该路由操作

Post路由

[php] Route::post('/','ControllerName@MethodName'); [/php]

只有当发起post请求时,才会触发该路由绑定的控制器 若直接访问该路由,将会抛出错误

Any路由(多请求路由)

[php] Route::any('/','ControllerName@MethodName'); [/php]

any路由其实就是post与get路由的结合体,可以通过使用post请求/get请求来访问该路由

Match路由(多请求路由)

[php] Route::match(['get','post'],'/','ControllerName@MethodName'); [/php]

在match路由中,该路由的第一个参数使用来配置该路由可以接受什么样的请求(详细可以接受什么样子的参数待以后再更新)


路由群组:

[php] Route::group(['prefix'=>'member'],function(){ Route::any('user/member-center',['as'=>'center',function(){ return route('center'); }]); Route::get('/basic1',function(){ return 'Hello world'; });//GET路由 }); [/php]

路由群组的作用: 可以把路由分门别类的放置到一个群组中,使用路由前缀进行访问 如localhost/member/basic1访问的就是位于member群组下的basic1路由


路由别名:

[php] Route::get('user/member-center',['as'=>'center',function(){ return route('center');//获取center路由的完整地址 }]); [/php]

路由别名的作用就是使用route时使用已预定好名字对应的路由 比如:route('center')对应的就是localhost/user/member-center 如果此时需要修改url仅需要在路由这修改,即可做到全项目修改


目前笔记先做到这里,如果有错再更新