控制器:
public function lists(Request $request){ $where = []; //條件搜索 if(!empty($request['type'])){ $where['type'] = $request['type']; } if(!empty($request['title'])){ $where['title'] = $request['title']; } if(!empty($request['author'])){ $where['author'] = $request['author']; } if($where){ //根據條件進行查詢 $data = Articles::lists2($where); $page = $data->currentPage();//當前頁 $num = $data->lastPage();//總頁數 return view('twelve.list',['arr'=>$data,'msg'=>'數據搜索','page'=>$page,'num'=>$num]); } //接收當前頁 $page = empty($request['page']) ? 1: $request['page']; //攔截 $json = Redis::get("article$page"); if($json){ $arr = json_decode($json,true); //在數組中提取想要的數據 $tableData = $arr['data'];//表格內容 $num = $arr['last_page'];//總頁數 return view('twelve.list',['arr'=>$tableData,'num'=>$num,'msg'=>'Redis查詢成功','page'=>$page]); } //先分頁查詢出數據(對象) $data = Articles::lists(); //先將對象想辦法轉化成數組(這里采用json互換的形式) $json = json_encode($data); $arr = json_decode($json,true); //在數組中提取想要的數據 $tableData = $arr['data'];//表格內容 $num = $arr['last_page'];//總頁數 //加入redis Redis::set("article$page",$json); //展示頁面 return view('twelve.list',['arr'=>$tableData,'num'=>$num,'msg'=>'Mysql查詢成功','page'=>$page]); }
模型層:
static public function lists(){ return self::paginate(10); } static public function lists2($where){ return self::where($where)->paginate(10); }
視圖層:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>列表</title> <link rel="stylesheet" href="css/bs.css"> </head> <body> <h1>{{$msg}}</h1> <form action=""> 分類:<input type="text" name="type"> 標題:<input type="text" name="title"> 作者:<input type="text" name="author"> <input type="submit" value="搜索"> </form> <table class="table"> <tr> <th>主鍵ID</th> <th>分類</th> <th>標題</th> <th>章節</th> <th>作者</th> <th>時間</th> <th>操作</th> </tr> @foreach($arr as $k=>$v) <tr> <td>{{$v['id']}}</td> <td>{{$v['type']}}</td> <td>{{$v['title']}}</td> <td>{{$v['last_title']}}</td> <td>{{$v['author']}}</td> <td>{{$v['time']}}</td> <td> <a href="">刪除</a> </td> </tr> @endforeach </table> <a href="lists?page=1">首頁</a> <a href="lists?page={{$page-1<=1 ? 1 : $page-1}}">上一頁</a> <a href="lists?page={{$page+1>=$num ? $num : $page+1}}">下一頁</a> <a href="lists?page={{$num}}">尾頁</a> </body> </html>