简体   繁体   English

Laravel $ request-> has('name')不起作用

[英]Laravel $request->has('name') doesn't work

I recently started using laravel to learn how to use it. 我最近开始使用laravel学习如何使用它。 Currently, I am handling forms and looking at the different methods that Laravel offers to facilitate our work but I can not see why the following code does not work: 当前,我正在处理表单,并查看Laravel提供的不同方法来简化我们的工作,但是我看不到以下代码为什么不起作用:

public function mensajes(Request $request) {
    //return $request->all();

    if ($request->has('nombre')){
        return "Sí tiene nombre. Es ". $request->input('nombre') ." y su correo es ". $request->input('email');
    } else {
        return "No tiene nombre";
    }



}

I try to verify that the form receives the input "name", but it receives it or not, it takes it as if it existed and if it was filled, however, when trying to execute this code if it does it correctly. 我尝试验证表单是否接收到输入的“名称”,但是无论是否接收到它,它都将其视为已存在且已被填充,但是,如果尝试正确执行此代码,它将被视为接受。

public function mensajes(Request $request) {
    //return $request->all();

    if ($request->input('nombre') != ''){
        return "Sí tiene nombre. Es ". $request->input('nombre') ." y su correo es ". $request->input('email');
    } else {
        return "No tiene nombre";
    }



}

I have a lot, maybe too much time watching my code, without seeing the error. 我有很多,也许太多的时间在看我的代码,而没有看到错误。

You should just be able to test if the nombre property of the request object is a falsy value (ie. does not exist, is empty, or is null ) by: 您应该能够通过以下方法测试请求对象的nombre属性是否为假值(即不存在,为空或为null ):

if($request->nombre) {
    //do something
} else {
    //do something else
}

If you are not using SanitizeMiddleware laravel will keep the input name as property in the request as an empty string ("") so ->has("name") method will return true always. 如果您不使用SanitizeMiddleware laravel会将输入名称作为请求中的属性保留为空字符串("")因此->has("name")方法将始终返回true

Do the following, on console: 在控制台上执行以下操作:

php artisan make:middleware SanitizeMiddleware

Then fill the new Middleware 然后填充新的中间件

   <?php

namespace App\Http\Middleware;

use Closure;

class SanitizeMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        foreach ($request->input() as $key => $value) {
            if (empty($value) || $value == "") {
                if($value !== '0')
                $request->request->remove($key);
            }
        }

        return $next($request);
    }
}

And register it on Kernel , within the web middleware group or wherever yo want to use it: 并将其注册在Web中间件组内的Kernel或您想使用它的任何地方:

    /**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        SanitizeMiddleware::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

This will remove empty inputs from incoming request so ->has("") should work now. 这将从传入请求中删除空输入,因此->has("")应该可以正常工作。

Read Laravel docs attentively, for proper usage of the HTTP Requests . 请认真阅读Laravel文档,以正确使用HTTP Requests

Determining If An Input Value Is Present 确定是否存在输入值

You should use the has method to determine if a value is present on the request. 您应该使用has方法来确定请求中是否存在值。 The has method returns true if the value is present on the request: 如果请求中存在该值,则has方法将返回true:

if ($request->has('name')) {
    //
}

If you would like to determine if a value is present on the request and is not empty, you may use the filled method: 如果要确定请求中是否存在一个值并且该值不为空,则可以使用filled方法:

if ($request->filled('name')) {
    //
}

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

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