网上搜了很多,感觉有些回答把问题复杂化了,没有必要写一大堆代码来重写这部分功能,只需要几行代码即可。
究其本质,就是三个东西:
下面详细说说怎么操作。
一、定义路由
| 1 | Route::get('/gov/page_{page}.html', [NoticeController::class, 'gov']); | 
定义好路由,并且在控制器中接收这个路由变量。
| 1 2 3 | public function gov($page = 1){ ***逻辑代码*** } | 
其他都不要改,先访问URL看路由是否正确,是否能访问,否则没必要往下。
二、withPath路径前缀
| 1 | $newNotice = Notice::orderBy('posted_time', 'desc')->paginate(10,['*'],'',$page)->withPath('page_'); | 
如上,传递page参数,以及定义withPath路径前缀。
三、定义一个后缀
打开这个路径,稍作修改:
| 1 | vendor\laravel\framework\src\Illuminate\Pagination\AbstractPaginator.php | 
找到public function url($page),在它前面插入以下代码:
| 1 2 3 4 5 6 7 8 |     protected $urlStr = '';      protected $ext = '.html';     public function withUrl($str) 	{ 		$this->urlStr =  $str; 		return $this; 	} | 
在url控制器内加入一个新的判断:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |     /**      * Get the URL for a given page number.      *      * @param  int  $page      * @return string      */     public function url($page)     {         //这里定义了前缀和后缀         if($this->path !=''){             return $this->path.$page.$this->ext;         }         if ($page <= 0) {             $page = 1;         }         // If we have any extra query string key / value pairs that need to be added         // onto the URL, we will put them in query string form and then attach it         // to the URL. This allows for extra information like sortings storage.         $parameters = [$this->pageName => $page];         if (count($this->query) > 0) {             $parameters = array_merge($this->query, $parameters);         }         return $this->path()                         .(str_contains($this->path(), '?') ? '&' : '?')                         .Arr::query($parameters)                         .$this->buildFragment();     } | 
保存,搞定!
原创文章,作者:蓝洛水深,如若转载,请注明出处:https://blog.lanluo.cn/12149
 
                
 微信扫一扫
                                                            微信扫一扫                                                     支付宝扫一扫
                                                            支付宝扫一扫                                                    