Laravel 5 $request->input与Input::get有何不同?

5

想知道以下两者之间有何区别:

$username = $request->input('username');

并且

$username = Input::get('username');

3
它们没有任何不同,除了 Input::get 已经被弃用(在文档中没有明确说明,但可以假设在阅读文档时使用 Request 是首选方式),因为在 Laravel 5.0 及更高版本的文档中没有提到它。 - Daan
1
请查看此链接:https://laravel.com/docs/4.2/requests - Yagnik Detroja
laravel.com/docs/4.2/requests 只提到了 Input::get,https://laravel.com/docs/5.2/requests 只提到了 $request->input。 - Jonh Doe
请注意:在 Laravel 6 中,Input 外观已被替换为 Request(https://laravel.com/docs/6.x/upgrade#the-input-facade)。 - Mateusz
2个回答

10

没有区别,外观模式Input从请求中调用输入方法。但Input::get已过时,请使用$request->input代替Input::get

<?php

namespace Illuminate\Support\Facades;

/**
 * @see \Illuminate\Http\Request
 */
class Input extends Facade
{
    /** 
     * Get an item from the input data.
     *
     * This method is used for all request verbs (GET, POST, PUT, and DELETE)
     *
     * @param  string  $key
     * @param  mixed   $default
     * @return mixed
     */
    public static function get($key = null, $default = null)
    {   
        return static::$app['request']->input($key, $default);
    }   

    /** 
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {   
        return 'request';
    }   
}

1
我发布的代码是Facade Input,位于vendor/laravel/framework/src/Illuminate/Support/Facades/Input.php - Jairo Correa

1

两者都是相同的,但这个内置了laravel功能,以便更好地使用laravel。

你可以两种方式都使用,但以下事项仅在INPUT中提供。只需一看。

  1. Input::has('name')

  2. Input::all()

  3. Input::only('username', 'password')

  4. Input::except('credit_card')

  5. Input::get('products.0.name')

还有这个

Input::get('username');

这样可以让事情更加简单。

如果我们使用这种方法,就需要编写更多的代码。

$request->input('username')

希望您能理解。谢谢。

2
这并不是真的,Input只是请求的门面,而Request也是请求的门面,这意味着Input使用请求的方法。如果你想要使用门面以提高实用性,你应该使用Facade Request而不是Input,例如:Request::all(); Request::has('name'); - Jairo Correa
@JairoCorrea是正确的。我们甚至可以使用 $data=$request->all() 从视图中获取所有数据。 - Don'tDownvoteMe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接