欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

laravel 路由器

程序员文章站 2024-02-12 17:37:34
...

web 页面路由都是在routes/web.php 文件中定义

不同的方法对应不同的http请求

Route::get($uri, $callback);

Route::post($uri, $callback);

Route::put($uri, $callback);

Route::patch($uri, $callback);

Route::delete($uri, $callback);

Route::options($uri, $callback);

注: POSTPUT 或 DELETE 路由的 HTML 表单请求都应该包含一个 CSRF 令牌,否则,这个请求将会被拒绝

1. 参数

Route::get('/index/{id}',function($id){echo $id;});
Route::get('/index/{id}/{num}',function($id,$num){echo $id;});
Route::get('/index/{id}/{num?}',function($id,$num=null){echo $id;});
Route::get('/index/{id?}/{num?}',function($id=null,$num=null){echo $id;});
Route::get('/index/{id}&{num}',function($id,$num){echo $id.$num;});
Route::get('/index/{id}/num/{num}',function($id,$num){echo $id.$num;});

 给参数加个正则:

Route::get('/index/{id}/num/{num}',function($id,$num){echo $id.$num;})->where('id', '[A-Za-z]+');

全局加正则:

可以 App\Providers\RouteServiceProvider.php  RouteServiceProvider 的 boot 方法里定义这些模式

public function boot()
{
    Route::pattern('id', '[0-9]+');

    parent::boot();
}

 

2.注册多个 HTTP 方法的路由

Route::match(['get', 'post'],'/index/{id}',function($id){echo $id;})
//全部
Route::any('/index/{id}',function($id){echo $id;});

 3.路由命名

// 生成 URL...
$url = route('profile');

// 生成重定向...
return redirect()->route('profile');

Route::get('/hello/{na}', function($na){
    echo 'hello world '.$na;
})->name('hello');

Route::get('/t',function(){
    return redirect()->route('hello',['na' => 'Nice']);
});

 3.路由组

   中间件 就是请求载入之间插件

Route::group(['middleware' => 'auth'], function () {
  
});

命名空间

在 app/http/controllers 下新键文件夹用作放控制器
Route::group(['namespace' => 'Admin'], function () {
  
   });

子域名
Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});