简体   繁体   English

如何将ID从url传递到laravel中的控制器

[英]How to pass ID from url to controller in laravel

I want my view page to open when the type the url as www.domain-name.in/sample/ID.我希望在将 url 键入为 www.domain-name.in/sample/ID 时打开查看页面。 ID can be an integer valure of 5 digits. ID 可以是 5 位整数值。 Right now my view page is opening when I type the url as www.domain-name.in/sample but when i type www.domain-name.in/sample/ID, I'm getting 404 error.现在,当我将 url 输入为 www.domain-name.in/sample 时,我的视图页面正在打开,但是当我输入 www.domain-name.in/sample/ID 时,我收到了 404 错误。 This is my route :这是我的路线:

 Route::get('/{$id}','HomeController@index');

This is my controller这是我的控制器

 public function index(Request $request,$id) { return view('filename'); }

How can I get view page with this url : www.domain-name.in/sample/ID如何使用此 url 获取查看页面:www.domain-name.in/sample/ID

Your route will be你的路线将是

Route::get('sample/{id}','HomeController@index')->where(['id' => '[0-9]{1,5}');

Your controller will be您的控制器将是

public function index($id)
{
   echo $id;
   exit;
   return view('filename');
}

Now you can access it as url as below.现在您可以通过以下网址访问它。

www.domain-name.in/sample/12345

"12345" is integer value of 5 digits sample id. “12345”是 5 位样本 ID 的整数值。

You need to use the below code:您需要使用以下代码:

If you defined route group in web.php then use:如果您在web.php定义了路由组,则使用:

Route::group(['prefix' => 'sample'], function(){
    Route::get('/{id}', 'HomeController@index')->name('home');
});

And in the controller:在控制器中:

public function index(Request $request,$id)
{
    $myid = $id;
    return view('filename', compact('myid'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM