Home > OS >  Laravel 9: error when i try to sign in (It doesnt) ¿Auth::Login?
Laravel 9: error when i try to sign in (It doesnt) ¿Auth::Login?

Time:07-12

I´m making a simple login/register system, the register part is working, but I have some problems with the login part. I´m working with Laravel 9 and docker, with MySQL. I have a Login Controller:

use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; //Es una clase para manejar autenticacion
use Illuminate\Contracts\Validation\Factory as ValidationFactory;


    class LoginController extends Controller
    {
    public function show(){
        return view('login');
    }

    public function login(LoginRequest $request){
        
        $credentials = $this->getCredentials(); //esto viene de la login request, puede ser el user y la contra o el mail y la contra

        if(!Auth::validate($credentials)){
            return redirect()->to('/login')->withErrors('Usuario o contraseña incorrectos');      
        }
        $user = Auth::getProvider()->retrieveByCredentials($credentials);
        Auth::login($user);
        return view('index');
    }

public function authenticated(Request $request, $user){
        return view('index');
    }

The LoginRequest.php file:

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;
class LoginRequest extends FormRequest
{
public function authorize()
    {
        return true;
    }
public function rules()
    {
        return [
            'user' => 'required|string|max:32',
            'password' => 'required|string|max:16',
        ];
    }

    public function getCredentials(){
        $user = $this->get('user');
        if($this->isEmail($user)){ //Si es un correo electronico la solicitud sera con un email
            return [
                'email' => $user,
                'password' => $this->get('password')
            ];
        }
        return $this->only('username', 'password');
    }
    
    public function isEmail($value){
        $factory = $this->container->make(Validation::class);
        return !$factory->make(['user' => $value], ['user' => 'email'])->fails();
    }
}

And the routes file Web.php with these two methods for login:

Route::get('/login', [LoginController::class, 'show']);

Route::post('/login', [LoginController::class, 'login']);

Now, when I put the sign in button in the page, with good credentials, it doesnt redirect me to Index page, it only reloads de login page with the next URL: https://gymreadyweb.ddev.site/login?_token=QrMFA1ug8coZCTXvS80ujEbEfBkR4QINWnfHUKtJ&user=gaspar&password=prueba1

If I do it with wrong credentials its the same. I don't know what more to do.

CodePudding user response:

Before my suggestion, I would like to recommend you... Please keep your code clean and try to follo DRY and SOLID paradigms.

Also I would like to suggest to do not re-invent the wheel.

I think your implementation can be simplified like this:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /** TODO: Document this... */
    public function show()
    {
        return view('login');
    }

    /** TODO: Document this... */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            "username" => "required_without:email|exists:users,username",
            "emai"     => "required_without:username|exists:users,email",
            "password" => "required",
        ]);

        if (Auth::attempt($credentials)) {
            return view('index');
        }

        return redirect(route('login'))->withErrors([
            "message" => "Usuario o contraseña incorrectos",
        ]);
    }

    /** TODO: Document this... */
    public function authenticated()
    {
        return view('index');
    }
}

Regarding to your routing schema, it's correct, I just recommend you to add a name to the routes, in my example I just use a login view name.

Route::get('/login', [LoginController::class, 'show'])->name("login");
Route::post('/login', [LoginController::class, 'login']);

CodePudding user response:

The mistake was as simple as change the view and set the form method to POST. Thank you all!

  • Related