Controller parameters via URL or POST

时间:2019-01-09 22:00:00

标签: php laravel laravel-5

I am using laravel to deliver a search page with the following routes:

Route::get('/search', 'PagesController@search');
Route::get('/search/{q}', 'PagesController@search');
Route::post('/search', 'PagesController@search');

The first route handles a visit to the search page which should display a search form. The second route expects a parameter on the URL that allows for bookmarking of searches. The third route receives the form from the first page as a POST and handles the search.

Each of three routes tries to use a single function within the PagesController.

public function search(Request $request)
{
    if ($request->has('q')) {
        $q = $request->input('q');
    }

    if ($q) {
        $models = Model::where('name', 'LIKE', "%{$q}%") 
                ->orderBy('name', 'desc')
                ->take(10)
                ->get();

        return view('pages.search', [ 'models' => $models, 'query' => $q ]);
    }

    return view ('home')->withMessage('No Details found. Try to search again !');       
}

My question is how do I get the single Controller function to handle the three routes? To pass in the {q} from the URL I think I need to add another parameter to the search function, but this then fails on the two routes that do not have the {q}.

In this situation is it a case of a separate function for each kind of response?

1 个答案:

答案 0 :(得分:0)

为了保持代码的清洁,我建议创建单独的函数。一种用于显示表单,一种用于POST,另一种用于书签。它比if分支更易于维护,更易于阅读。

但是,要直接回答您的问题,可以根据需要将其全部合并。只需向方法添加一个可选参数,如下所示:

public function search(Request $request, $q = false){}

通过将$q的默认值设置为false,不带变量的传入路由不会失败。它还允许进行简单的if-check(if($q)...)。

HTH