如何在laravel中传递查询字符串5.4

问题描述:

我正在使用Laravel 5.4。我想要使​​用如下查询字符串:如何在laravel中传递查询字符串5.4

tempsite.com/lessons?id=23 

为了得到这个如何修改路由。可以通过以下方式给出路线。

Route::get('lessons/id={id}', ['as' => 'lessons.index', 'uses' => 'Lessons\[email protected]']); 

但添加'?'不适合我。请尽早帮助我们提供解决方案。

如果使用的是足智多谋的控制器,你的路线,你都处理,这样你就干脆把

Route::resource('lessons', 'Lessons\LessonController'); 

然后,您可以使用路径模型,结合其特定的ID匹配的模型实例绑定。

Route::model('lesson', Lesson::class); 

这将在您的RouteServiceProvider中完成。

我还建议在laravel网站https://laravel.com/docs/5.4/routing上阅读以下文档。它对路线如何运作以及如何构建路线提供了非常好的见解。

而不是tempsite.com/lessons?id=23 它传递这样tempsite.com/lessons/23 ,在该路由

Route::get('lessons/{id}', ['as' => 'lessons.index', 'uses' => 'Lessons\[email protected]']); 

获得ID在你的控制器,写你的函数像这样

public function index($id) 
{ 
    //do anything with $id from here 
} 
+0

这并不回答这个问题。虽然在这个特定的情况下,最好将它作为一个有意义的URL传递,但是有时候querystrings仍然更好。 –

没有必要在你的路由中定义查询字符串参数。您可以在您的控制器像这样返回的查询字符串参数:

URL例如:tempsite.com/lessons?id=23

public function lessons(Request $request) 
{ 
    $request->get('id'); // Using injection 
    Request::get('id'); // Using the request facade 
    request()->get('id'); // Using the helper function 
} 

你甚至可以验证参数:

public function lessons(Request $request) 
{ 
    $this->validate($request, ['id' => 'required|integer']); 
} 

注:如果您希望在省略ID的情况下使URL无法访问,请参阅@DarkseidNG答案。