In today’s tutorial we will learn how to customise the Laravel auth scaffolding and use AJAX for login in Laravel.
As authentication feature in Laravel comes in built with Laravel once we run it’s artisan command, it is one of the most easiest of functionalities to achieve with Laravel. Having said that, any sort of customisation to the authentication process becomes quite challenging and overwhelming since it Laravel serves it with amazing depth.
Let’s follow the below mentioned simple steps to customise the Laravel login functionalities with AJAX.
Step 1: The setup
Like any other project our first and most obvious step would be get a fresh installation of Laravel project and set up the database connection.
Next we will run the artisan command inside our project folder to generate the authentication scaffolding.
php artisan make:auth
Now, we will be able to see all files related to authentication. We are going to cover only some of these files and modify a bit to achieve our goal for today.
If we browse to database/migrations, we will see that Laravel already has the migrations we need for authentication ready for us.
So, let’s run the migration
php artisan migrate
Now, if we run php artisan serve and run the project in browser we will see that, our project is having proper authentication features like registration,login, forgot password, reset password etc running flawlessly.
Step 2: The Javascript
Now, we will take care of the js part of our application. As we will be relaying of jQuery mostly in our application, we will remove the front end scaffolding which comes with example vue components.
php artisan preset none
We can also simply remove the example vue components manually.
Now, we will install our js dependencies.
npm install
For front end validation we will use jquery validation plugin.
npm install jquery-validation --save
Now we will open up our resources/assets/js/app.js file and include the additional files we need for AJAX authentication.
This app.js file is compiled with laravel mix and saved in the public folder which is included in our app.blade.php layout file.
import 'jquery-validation/dist/jquery.validate.min.js';
We will write our validation and AJAX function in a separate file called login.js. Let’s also include this file here.
require('./login');
Now we will compile our JS files with a watch flag so that any further changes get compiled on the go.
npm run watch
To target the log in form with jQuery, we will open resources/views/auth/login.blade.php and give the form an id of loginForm.
We will also add a label inside the form where we will show error messages in case the authentication fails.
<label class="alert alert-danger" id="errorMsg"></label>
Next, we will open up our resources/assets/js/login.js and take care of the validation part.
$('#loginForm').validate({ rules:{ email:{ required:true, email:true }, password:{ required:true } }, messages:{ email:{ required:"Please enter an email address.", email:"Please enter a valid email address." }, password:{ required:"Please enter a password." } }, submitHandler:function(form){ //AJAX form submission will go here } })
Now we will write our code to handle the login with AJAX.
submitHandler:function(form){ var formurl = $(form).attr('action'); $.ajax({ url: formurl , type: "POST", data: new FormData(form), cache: false, processData: false, contentType: false, success: function(data) { }, error:function(xhr){ } }); }
Step 3: The Controller
The requisite routes and logic to handle authentication comes with the auth scaffolding in Laravel itself. If we open app/Http/Controllers/Auth/LoginController.php, we can see that all login related functionalities are written inside AuthenticatesUsers trait.
If we write a method in our LoginController.php file with same name as in the trait, the code for that method in the trait gets overwritten.So, if our controller file we will write the code for the method that gets called once the user is successfully authenticated.
use Illuminate\Http\Request;
protected function authenticated(Request $request, $user) { if ($request->ajax()){ return response()->json([ 'auth' => auth()->check(), 'user' => $user, 'intended' => $this->redirectPath(), ]); } }
And that is all the logic we need to write in our controller.
Step 4: Finishing Touches in Javascript
Now, we will handle our AJAX success and callback methods to complete our goal.
success: function(data) { if(data.auth) window.location.href = SITE_URL+data.intended; else $('#loginForm #errorMsg').text('Some error occured, please try again!'); }, error:function(xhr){ console.log(xhr.responseJSON.message); $('#loginForm #errorMsg').text(xhr.responseJSON.message); }
Notice, the variable SITE_URL we are using to handle our redirect. We will define this in our resources/assets/js/bootstrap.js file with our project URL.
window.SITE_URL="http://localhost:8000/";
Our AJAX login with Laravel 5.6 is now ready.The full source code is available on Github here.
If you have any queries or suggestions do let me know in the comments below or drop an email to ask@webdevelopmentsolutions.net.
Happy Coding
来自 https://webdevelopmentsolutions.net/laravel-5-6-ajax-login/
Laravel Login with AJAX
How can i properly integrate an ajax login with Laravel? Can i use AngularJS for this?