【问题标题】:Laravel get the parameter of url in controllerLaravel 获取控制器中 url 的参数
【发布时间】:2018-09-13 10:14:00
【问题描述】:

我正在尝试将参数的值放入变量中,这就是我目前所拥有的:

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

    return view('test.test1');
}

我的路线是:

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

我得到的输出是NULL 如何获取url参数的值?

我的网址是:

localhost/test/test1/4

所以我想输出 4。

我尝试做 thr request 方法但没有用所以它和Passing page URL parameter to controller in Laravel 5.2不一样

【问题讨论】:

标签: php laravel laravel-5


【解决方案1】:

您应该在 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'));
}

【讨论】:

    【解决方案2】:

    请使用url中的id作为控制器功能参数

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

    【讨论】:

    • 参数列表中的第一个逗号不应该在那里public function something(Request $request, $id){ return $id; }
    【解决方案3】:

    web/routes.php

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

    控制器文件

    public function getname(Request $request,$id)
    {
    
        echo $id; # will output 4
        $param = $id;
        return view('test.test1')->with('param',$param);
    }
    

    【讨论】:

      【解决方案4】:

      很简单,你可以在你的控制器里跟着这段代码

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

      输出:localhost/test/test1/4

      【讨论】:

        猜你喜欢
        • 2018-05-31
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        • 2015-02-07
        • 1970-01-01
        • 2020-05-24
        • 1970-01-01
        • 2018-03-16
        相关资源
        最近更新 更多