简体   繁体   English

Laravel 在控制器中获取 url 的参数

[英]Laravel get the parameter of url in controller

I'm trying to get a value of the parameter in to a variable this is what I have so far:我正在尝试将参数的值放入一个变量中,这是我到目前为止所拥有的:

public function getname(Request $request)
{
    echo ($request->input('id'));

    return view('test.test1');
}

and my route is:我的路线是:

Route::get('/test/{id}','Controller@getname');

the output I get is NULL how can I get the value of the url parameter?我得到的输出是NULL我怎样才能得到 url 参数的值?

my url is:我的网址是:

localhost/test/test1/4

so I want 4 to be outputed.所以我想输出 4。

I tried doing thr request method but didn't work so it's not the same as Passing page URL parameter to controller in Laravel 5.2我尝试执行 thr 请求方法,但没有奏效,因此它与将页面 URL 参数传递给 Laravel 5.2 中的控制器不同

web/routes.php网页/routes.php

Route::get('/test/{id}','Controller@getname');

Controller file控制器文件

public function getname(Request $request,$id)
{

    echo $id; # will output 4
    $param = $id;
    return view('test.test1')->with('param',$param);
}

Please use the id in url as controller function parameters请使用 url 中的 id 作为控制器函数参数

public function something(Request $request,$id){
    return $id;
} 

You should add extra parameters to your getName function.您应该向 getName 函数添加额外的参数。

# Stick to the convention of camelcase functions, not getname but getName
public function getName(Request $request, $param, $id)
{
    # This only works when you pass an id field while performing a POST request.
    # echo ($request->input('id'));
    echo $param; # will output 'test1'
    echo $id; # will output 4
    return view('test.test1', compact('$param','id'));
}

very simple, you can follow this code in your controller非常简单,您可以在控制器中遵循此代码

$url = url()->current();
$url = str_replace("http://", "", $url);
dd($url);

output: localhost/test/test1/4输出:本地主机/测试/测试1/4

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

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