Laravel 6 路由常见用法

时间:2021-07-16
本文章向大家介绍Laravel 6 路由常见用法,主要包括Laravel 6 路由常见用法使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Laravel 路由的几种常见模式

1.基础路由get、post

Route::get('myget',function(){
      return 'this is get';
});

Laravel 中post有个csrf保护在使用postman进行测试的时候需要进入Http的中间件Middleware在VerifyCsrfToken中的except中添加路由名即可

Route::post('mypost',function(){
      return 'this is post';
});

2.多请求路由match、any

Route::match(['get','post],'match',function(){
      return 'this is get and post';
});
Route::any('any',function(){
      return 'this is request from any http verb';
});

3.CSRF保护

这里需要在这加一个csrf的令牌这样请求才会被接收

Route::get('form',function(){
      return '<form method="post" action="any">.csrf_field().'<button type="submit">提交</buttton></form>';
});

4.视图路由

访问路由名routeview就可以访问到welcome页面,这里的中括号是演示了当你访问路由名为website的时候把'jellysheep'这个值传到welcome界面里的{{$website}}显示

Route::view('routeview','welcome',['website'=>'jellysheep']);

5.路由参数

单个参数

Route::get('user/{id}',function($id){
      return 'user='.$id;
 });

多个参数

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

可选参数 在参数后加一个问号并赋予一个初始值

Route::get('user/{id?}/name/{name?}',function($id='1',$name='jelly'){
      return 'user='.$id.'name='.$name;
 });

单个参数的正则约束

Route::get('user/{name}',function($name){
      return 'user='.$name;
 })->where('id','[A-Za-z]+');

多个参数的正则约束

Route::get('user/{id}/name/{name}',function($id,$name){
      return 'user='.$id.'name='.$name;
 })->where(['id'=>'[0-9]+','name'=>'[A-Za-z]+']);

全局范围内进行约束:需要在app的Provides里的RouteServiceProvider中的boot方法定义一下约束方式. 那么在所有路由中包含了这个参数名,那么都会对这个参数进行约束

Route::pattern('id','[0-9]+');

6.命名路由

主要是为了生成url和重定向提供了一个非常方便的一个方式

Route::any('user/profile',function(){
      return 'myurl:'.route(name:'profile'); 
})->name('profile');
//重定向路由
Route::any('redirect',function(){
      return redirect()->route(route:'profile'); 
});

可以使用as关键字

原文地址:https://www.cnblogs.com/jellysheep/p/15020905.html