请教 request () 中的 input () 方法 和 get () 方法 有什么区别,请大神指点一下

请教大神们详细说一下这两个 方法有什么区别,在此感谢了

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3

两个都可以获取用户输入的数据,不同的是, get() 方法是 Symfony\Component\HttpFoundation\Request 提供的一个方法,他的源码是这样的。

public function get($key, $default = null)
{
    if ($this !== $result = $this->attributes->get($key, $this)) {
        return $result;
    }

    if ($this !== $result = $this->query->get($key, $this)) {
        return $result;
    }

    if ($this !== $result = $this->request->get($key, $this)) {
        return $result;
    }

    return $default;
}

在Laravel中是不推荐使用的,Laravel中推荐使用的是Laravel自己的方法 input()

6年前 评论

input() 方法是 Laravel框架自带的方法, 在 Illuminate\Http\Request里, Request 继承的是Symfony\Component\HttpFoundation\Request

/**
     * Retrieve an input item from the request.
     *
     * @param  string  $key
     * @param  string|array|null  $default
     * @return string|array
     */
    public function input($key = null, $default = null)
    {
        $input = $this->getInputSource()->all() + $this->query->all();

        return Arr::get($input, $key, $default);
    }

get() 方法则在 Symfony框架中, 在 Symfony\Component\HttpFoundation\Request

/**
     * Gets a "parameter" value.
     *
     * This method is mainly useful for libraries that want to provide some flexibility.
     *
     * Order of precedence: GET, PATH, POST
     *
     * Avoid using this method in controllers:
     *
     *  * slow
     *  * prefer to get from a "named" source
     *
     * It is better to explicitly get request parameters from the appropriate
     * public property instead (query, attributes, request).
     *
     * @param string $key     the key
     * @param mixed  $default the default value if the parameter key does not exist
     * @param bool   $deep    is parameter deep in multidimensional array
     *
     * @return mixed
     */
    public function get($key, $default = null, $deep = false)
    {
        if ($this !== $result = $this->query->get($key, $this, $deep)) {
            return $result;
        }

        if ($this !== $result = $this->attributes->get($key, $this, $deep)) {
            return $result;
        }

        if ($this !== $result = $this->request->get($key, $this, $deep)) {
            return $result;
        }

        return $default;
    }

两者都是获取请求参数的值

6年前 评论
ruke

有些情况下get会取不到值, 用input可以取到, 我上次除了一次bug, 就是因为get没取到值

6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!