Laravel框架中Form表单Get请求搜索(在此感谢[https://simon8.com])

时间:2022-04-03 08:35:57

首先看一下HTML部分的Form表单

<form role="search" method="get" id="searchform" action="{{ route('mysearch') }}">
<input type="search" name="keyword" placeholder="关键字" required>
<button type="submit"><span class="ion-ios-search-strong"></span></button>
</form>

PHP文件中的路由配置

Route::get('/search','Home\SearchController@index')->name('mysearch');

PHP文件中的控制器部分

<?php

namespace App\Http\Controllers\Home;

use App\Http\Model\Home\Article;
use Illuminate\Http\Request;
use App\Http\Requests; class SearchController extends CommonController
{
//请求地址
public function index(Request $request){
$getKeyWord = $request->keyword;
$all_article = (new Article)->searchArticle($getKeyWord);
// foreach($all_article as $v){
// $v->title = str_ireplace($getKeyWord,'<font color="#FF0000">'
.$getKeyWord.'</font>',$v->title);
// }
return view('home.search.index',compact('all_article','getKeyWord'));
}
}

要修改的文件路径

J:\wamp64\www\laravel\vendor\laravel\framework\src\Illuminate\Pagination\UrlWindowPresenterTrait.php

首先修改的是第一个方法getLinks

protected function getLinks()
{
$html = '';
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$pase_url = parse_url($url);
$url_query = '';
if(strpos($url,'search?keyword') !== false){
$url_query = $pase_url['query'];
$url_query = strpos($url_query,'&') !== false ? substr($url_query,0,strpos($url_query,'&'))
: $url_query;
}
if (is_array($this->window['first'])) { //在测试中,始终走的是当前流程,所以给传了一个字符串类型的参数
$html .= $this->getUrlLinks($this->window['first'],$url_query);
} if (is_array($this->window['slider'])) {
$html .= $this->getDots();
$html .= $this->getUrlLinks($this->window['slider']);
} if (is_array($this->window['last'])) {
$html .= $this->getDots();
$html .= $this->getUrlLinks($this->window['last']);
}
return $html;
}

找到当前类中getUrlLinks方法,然后修改,直接在当前方法内处理返回了

protected function getUrlLinks(array $urls,$url_query = '')
{
$html = '';
foreach ($urls as $page => $url) {
$html .= $this->getPageLinkWrapper($url, $page);
}
if($url_query != '' && strpos($url_query,'keyword') !== false){ $html_str = htmlspecialchars($html); if(strpos($html_str,'search?') !== false){
$html = htmlspecialchars_decode(str_replace('search?','search?'.$url_query.'&',$html_str));
}
}
return $html;
}

经过测试行得通