1

LoginController.php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = '/';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}
protected function credentials(Request $request)
{
$login = $request->input($this->NombreCompleto);

return [
$field => $login,
‘password’ => $request->input('password')
];
}
}

RegisterController.php

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'NomCom' => 'required|string|max:255',
            //'dni' => 'required|string|email|max:255|unique:users',
            'dni' => 'required|string|max:255',
            'password' => 'required|string|min:6|confirmed',
            'DirecEnv' => 'required|string|max:255',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            // 'name' => $data['name'],
            // 'email' => $data['email'],
            // 'password' => Hash::make($data['password']),
            'dni' => $data['dni'],
            'NombreCompleto' => $data['NomCom'],
            'password' => Hash::make($data['password']),
            'DireccionEnvio' => $data['DirecEnv'],
        ]);
    }
}

auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'password',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
            'table' => 'clientes',
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('Nombre de Usuario') }}</label>

                            <div class="col-md-6">
                                <input id="NomCom" type="text" class="form-control{{ $errors->has('NomCom') ? ' is-invalid' : '' }}" name="NomCom" value="{{ old('NomCom') }}" required autofocus>

                                @if ($errors->has('NomCom'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('NomCom') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>


                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

register.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Register') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('register') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="NomCom" class="col-md-4 col-form-label text-md-right">{{ __('Nombre de Usuario') }}</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control{{ $errors->has('NomCom') ? ' is-invalid' : '' }}" name="NomCom" value="{{ old('NomCom') }}" required autofocus>

                                @if ($errors->has('NomCom'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('NomCom') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="dni" class="col-md-4 col-form-label text-md-right">{{ __('DNI') }}</label>

                            <div class="col-md-6">
                                <input id="dni" type="text" class="form-control{{ $errors->has('dni') ? ' is-invalid' : '' }}" name="dni" value="{{ old('dni') }}" required>

                                @if ($errors->has('dni'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('dni') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="DirecEnv" class="col-md-4 col-form-label text-md-right">{{ __('Direccion de Envio') }}</label>

                            <div class="col-md-6">
                                <input id="DirecEnv" type="text" class="form-control{{ $errors->has('DirecEnv') ? ' is-invalid' : '' }}" name="DirecEnv" value="{{ old('DirecEnv') }}" required>

                                @if ($errors->has('DirecEnv'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('DirecEnv') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="invalid-feedback">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>

                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Registrarse') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $table = 'clientes';
    protected $primaryKey = 'id';
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public $timestamps = false;
    protected $fillable = [
        'dni', 'dni', 'NombreCompleto', 'password', 'DireccionEnvio', 'Fecha1', 'Fecha2',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

routes/web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

bbdd

TABLE `clientes` (
  `id` int(2) NOT NULL,
  `dni` varchar(10) COLLATE utf8_spanish_ci NOT NULL,
  `NombreCompleto` varchar(30) COLLATE utf8_spanish_ci NOT NULL,
  `password` varchar(200) COLLATE utf8_spanish_ci NOT NULL,
  `DireccionEnvio` varchar(30) COLLATE utf8_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;

He estado intentando hacer un registro y inicio de sesión con laravel 5.6 y he conseguido registrar un usuario y guardar los datos en la bbdd pero en el momento de iniciar sesion me redirige a la misma pagina de login, aunque ponga los datos mal me redirige a la misma página de login, creo que es porque tengo que añadir algo en el auth.php para que coja el campo "NombreCompleto" de la tabla clientes como nombre de usuario ya que por defecto viene Email, pero no se como editar ese fichero.

1
  • Puedes hacer algo como php artisan make:auth lo cual te servirá como base y podrás hacer tus posteriores logins
    – Wilfrido
    Commented el 21 mar. 2018 a las 1:27

2 respuestas 2

3

Agrega en el archivo app\Htpp\Controllers\Auth\LoginController.php esta linea:

public function username()
{
    return 'NombreCompleto';
}

Modifica en las vista login el nombre del campo como lo definiste en el username:

<div class="form-group row">
<label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('Nombre de Usuario') }}</label>
<div class="col-md-6">
    <input id="NombreCompleto" type="text" class="form-control{{ $errors->has('NombreCompleto') ? ' is-invalid' : '' }}" name="NombreCompleto" value="{{ old('NombreCompleto') }}" required autofocus>
    @if ($errors->has('NombreCompleto'))
     <span class="invalid-feedback">
        <strong>{{ $errors->first('NombreCompleto') }}</strong>
     </span>
    @endif
</div>

Y en el register tambien:

<div class="form-group row">
<label for="NombreCompleto" class="col-md-4 col-form-label text-md-right">{{ __('Nombre de Usuario') }}</label>
<div class="col-md-6">
    <input id="name" type="text" class="form-control{{ $errors->has('NombreCompleto') ? ' is-invalid' : '' }}" name="NombreCompleto" value="{{ old('NombreCompleto') }}" required autofocus>
    @if ($errors->has('NombreCompleto'))
        <span class="invalid-feedback">
            <strong>{{ $errors->first('NombreCompleto') }}</strong>
        </span>
    @endif
</div>

Igual en los metodos validator

En esta linea colocaste dos veces dni:

protected $fillable = [
    'dni', 'dni', 'NombreCompleto', 'password', 'DireccionEnvio', 'Fecha1', 'Fecha2',
];
3
  • Gracias, funciona añadiendo estas lineas y modificando el "validator" y el "create" del RegisterController, hay alguna diferencia entre esta forma y la que mencionan otros comentarios de modificar el archivo "vendor > laravel > framework > src > Illuminate > Foundation > Auth > AuthenticatesUsers.php "? Commented el 21 mar. 2018 a las 16:15
  • Si hay diferencia ya que los archivos que están en la carpeta vendor no debes modificarlos ya que esta es creada y modificada por composer, en el momento en el que necesites actualizar tus dependencias con composer update se perderan todas tus modificaciones, puedes leer mas al respecto aqui: laraveles.com/…
    – FQuijada
    Commented el 21 mar. 2018 a las 16:46
  • me ayudo mucho la info, yo tengo una consulta . Y si quiero que el login sea por ambos, tanto por username como por email, como seria! ? Commented el 15 jul. 2019 a las 11:54
0

Lo probe en versión 5.5 pero puedes intentar en la carpeta vendor > laravel > framework > src > Illuminate > Foundation > Auth > AuthenticatesUsers.php

Como a la mitad vienen unas lineas asi

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|string',
        'password' => 'required|string',
    ]);
}

puedes cambiar el $this->username() por el campo que necesites

si te fijas en tu LoginController.php viene esta linea

use Illuminate\Foundation\Auth\AuthenticatesUsers;

asi llegas a la carpeta que necesitas Espero te funcione

2
  • No es recomendado editar los archivos de la carpeta vendor estos deberian ser manejados por el manejador de dependencias composer y tambien se suele dejar el contenido de esta carpeta fuera del control de versiones, puedes leer mas al respeto aqui: laraveles.com/…
    – FQuijada
    Commented el 21 mar. 2018 a las 13:25
  • @FranciscoQuijada Interesante, gracias ! Commented el 22 mar. 2018 a las 1:57

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.