求助:Laravel搜索栏从$_GET改为$_POST的实现方法
把Laravel搜索栏从GET请求改为POST请求的修改方案
1. 修改视图表单
将表单的请求方式从GET改为POST,同时添加Laravel必需的CSRF令牌,还修正了输入框的class拼写错误:
<body> <div class="container d-flex justify-content-end"> <div class="row"> <div class="col-md-12"> <form action="{{ route('search_bar_route') }}" method="POST"> @csrf <div class="form-group"> <input type="text" class="form-control" name="query" placeholder="Search Competitions" value="{{ old('query') }}" /> <button type="submit" class="btn btn-primary btn-sm ms-1 mb-1"> Search <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16" > <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z" /> </svg> </button> </div> </form> </div> </div> </div> </body>
- 新增
value="{{ old('query') }}"是为了提交表单后,输入框能保留用户的搜索关键词。
2. 修改控制器逻辑
改用Laravel的Request类获取POST参数,同时处理分页时的参数传递问题(POST请求的分页链接默认是GET,需要手动附加搜索参数):
use Illuminate\Http\Request; use App\Models\Competition; // 确保引入模型 public function index(Request $request) { $query = $request->input('query'); // 初始化查询构造器 $competitionsQuery = Competition::orderBy('id', 'DESC'); if ($query) { $competitionsQuery->where('name', 'LIKE', '%' . $query . '%'); // 分页时携带搜索参数,保证分页后依然保持搜索状态 $competitions = $competitionsQuery->paginate(1)->appends(['query' => $query]); } else { $competitions = $competitionsQuery->paginate(40); } return view('competition.index', compact('competitions', 'query')); }
3. 修改路由定义
将路由的请求方式从GET改为POST:
Route::post("/search", [CompetitionController::class, 'index'])->name('search_bar_route');
额外说明
- POST请求的搜索参数不会出现在URL中,无法直接分享搜索结果链接,也不能通过刷新页面保留搜索状态,如果有这类需求,GET请求会更合适。
- 确保控制器顶部正确引入了
Competition模型和Request类。
内容的提问来源于stack exchange,提问作者Yorkata008
相关产品推荐
相关产品推荐

