skip to Main Content

I am new to Laravel and I am using ajax validation in Laravel 10.

The issue is, the validation is working, when my login credentials are incorrect, but when i try to use valid credentials, it is not redirecting to dashboard, rather it redirects to the login page

Below is my controller:

public function loginUser(Request $request){
        $validator = Validator::make($request->all(), [
            'username' => 'required|max:50',
            'password' => 'required|min:6|max:100'

        ]);

        if($validator->fails()){
            return response()->json([

                'status' => 400,
                'messages' => $validator->getMessageBag()
            ]);
        }else{
            $user = User::where('username', $request->username)->first();
            if($user){
                if(Hash::check($request->password, $user->password)){
                    $request->session()->put('loggedInUser', $user->id);
                    return response()->json([
                        'status' => 200,
                        'messages' => 'success'
                    ]);

                } else{
                    return response()->json([
                        'status' => 401,
                        'messages' => 'Username or password is incorrect!'
                    ]);
                }
            } else{
                return response()->json([
                    'status' => 401,
                    'messages' => 'Uername not found!'
                ]);
            }
        }
    }

Routes:

Route::controller(AdminController::class)->group(function() {
    Route::post('auth.register', 'saveUser')->name('auth.register');
    Route::post('auth.login', 'loginUser')->name('auth.login');
});

Blade:

<script>
        $(function(){
            $("#loginForm").submit(function(e){
                e.preventDefault();
                $("#loginBtn").val('Please wait...');
                $.ajax({
                    url: '{{ route('auth.login') }}',
                    method: 'post',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function(res){
                        if(res.status == 400){
                            showError('username', res.messages.username);
                            showError('password', res.messages.password);
                            $("#loginBtn").val('Login');
                        } else if(res.status == 401){
                            $("#login_alert").html(showMessage('danger', res.messages));
                            $("#loginBtn").val('Login');
                        } else {
                            if(res.status == 200 && res.messages == 'success'){
                                window.location = '{{ route('dashboard') }}';
                            }
                        }
                    }
                });
            });
        });
    </script>

2

Answers


  1. There are a few problems here. first ajax isn’t used for redirecting/routing but I see what you did here to get around that. also you shouldn’t inject the dash board url like that directly into javascript. it should look something like this…

    <script>
        var app = {{ Js::from($array) }};
    </script>
    

    also you are attempting to rewire how Laravel authentication works. I can’t remember but their user session hasn’t been started until you move to an authenticated route. however, you should just simply not just add user data to the session assuming that will just work. you will need an authentication or authorization cookie that holds your user data and session id. try using laravel breeze or sanctum (https://laravel.com/docs/10.x/starter-kits) package which will install the login controllers and routes you may need for authentication. look more in the authentication middleware and authcontrollers. the user will also need to implement the canlogin (or something like that) interface which they have a trait for but if you prefer not to use it you will need to build something to implement that and hasapitoken as well if you plan to consume your own API. also look into Laravel passport.

    https://Laravel.com

    also this doesn’t work '{{ route('dashboard') }}' you are creating a string {{ route( ) }} with a variable dashboard in the middle. why not try hard coding that first?

    Login or Signup to reply.
  2. If you are using a SPA and Laravel as API with Sanctum authentication, a fresh Laravel installation+Breeze api scaffolding will be enough to get what you are looking for.

    The file appProvidersRouteServiceProvider.php already has a constant named ‘Home’ which is initialized by default with '/Dashboard'. Such route must be defined and its respective view, in order to work properly.

    For a SPA to work with Laravel API you need to create a domain and subdomain (localhost doesn’t work because it is not a TLD) with their respective certificates to use HTTPS to move secure cookies/headers from one end to the other.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search