Php – Laravel $request->has(‘name’) doesn’t work

laravelphp

I recently started using laravel to learn how to use it. 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:

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.

Best Solution

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:

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