Skip to main content
  • 博客
    • div+css 博客
    • javascript 博客
      • vue 博客
    • php 博客
      • 微信 博客
  • php
    • drupal
    • composer
    • thinkphp
    • onethink
    • laravel
    • Swoole
    • dedecms
    • magento
    • smarty
    • ecshop
    • zencart
    • joomla
    • discuz
    • wordpress
    • yii
    • 微信
    • 抖音
    • ci
    • weiphp
    • destoon
  • python
    • plone
  • apache
  • nginx
  • cache
    • memcache
    • redis
  • div+css
  • javascript
    • jquery
    • typescript
    • Vue.js
    • Amaze
    • zepto
    • react
    • underscore
    • backbone
    • angular
    • lodash
    • layui
    • js特效
  • vbscript
  • photoshop ai
  • sql
    • mysql
    • mssql
    • oracle
  • regular
  • node.js
  • 腾讯开放平台
  • dreamweaver
  • linux
  • seo
  • app
  • asp及asp.net
  • flash
  • iis
  • java
  • mac
  • wap
  • windows
    • dos
    • 打印机
  • 其它
  • 浏览器
  • 网络
  • AD域 (exchange)
  • 虚拟机
  • AC
  • ai
  • 简写翻译

欢迎各位兄弟 发布技术文章

这里的技术是共享的

个人技术网_前端_后台_php_div_css_linux_javascript_seo 个人技术网_前端_后台_php_div_css_linux_javascript_seo

搜索表单

用户登录

  • 重设密码

You are here

首页

Laravel AJAX user login 用户登录 有大用

星期二, 2019-08-13 09:59 — adminshiping1

aaaaa

aravel 5.6 AJAX user login

               

WEB DEVELOPMENT SOLUTIONS                

Learning web development together

Laravel, PHP                                    

Laravel 5.6 AJAX login

Arup / April 8, 2018                                    
laravel ajax login                                

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/                                    


aaaaa

MarkMatute•                        
Jul 5, 2015                        
4153                            
12                            
REQUESTS                        

Laravel Login with AJAX

How can i properly integrate an ajax login with Laravel? Can i use AngularJS for this?

skliche                                
Level 35                                
skliche•Jul 5, 2015                                        

@MarkMatute Do you get any error or exception details in the ajax response, anything in your log files? HTTP 500 means that something on your server side went wrong.

                           
mattkomarnicki                                
Level 1                                
mattkomarnicki•Jul 5, 2015                                    

It's easy. Re-use your existing POST route for $.ajax and inside your authenticate method check request type. If you will detect ajax post request then simply as a response return a json with either true or false + any additional data you need.

2                                    
                               
mattkomarnicki                                
Level 1                                
mattkomarnicki•Jul 5, 2015                                    

@MarkMatute:

public function postLogin(Request $request)
{
    $auth = false;
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials, $request->has('remember'))) {
        $auth = true; // Success
    }

    if ($request->ajax()) {
        return response()->json([
            'auth' => $auth,
            'intended' => URL::previous()
        ]);
    } else {
        return redirect()->intended(URL::route('dashboard'));
    }
    return redirect(URL::route('login_page'));
}
                               
6                                    
                               
MarkMatute                                
Level 1                                
MarkMatute•Jul 5, 2015                                    

@slick i cant send my ajax request, im getting errors, POST http://localhost:8000/auth/auth/login 500 (Internal Server Error) and this is my code ''' $(document).ready(function(){

var loginForm = $("#loginForm");
loginForm.submit(function(e){
    e.preventDefault();
    var formData = loginForm.serialize();

    $.ajax({
        url:'auth/login',
        type:'POST',
        data:formData,
        success:function(data){
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });
});

alert('Successfully Loaded');
                                   

});

'''

                           
skliche                                
Level 35                                
skliche•Jul 5, 2015                                        

@MarkMatute Do you get any error or exception details in the ajax response, anything in your log files? HTTP 500 means that something on your server side went wrong.

                           
spekkie2002                                
Level 3                                
spekkie2002•Oct 8, 2015                                        

You can check your log files under the storrage/logs folder... Probably your 500 error can be resolved there :-)

Good luck

                           
jlrdw                                
Level 50                                
jlrdw•Oct 8, 2015                                        

Ajax shouldn't be used for login, I never even send any secure information through ajax.

                           
cimrie                                
Level 4                                
cimrie•Oct 8, 2015                                        

I would disagree about not using AJAX - while I haven't used it myself, it should behave (or you can make it behave) exactly like a POST request from a form - especially if you also make sure CSFR protection is in place - and so its just a nice UX addition. Stripe effectively use AJAX for sending card details across the wire, so I wouldn't worry. If you're ever worried about security just slap an SSL (even if it is self-signed) on the page and all AJAX & form requests will be secured through that.

2                                    
                               
igor_talevski                                
Level 3                                
igor_talevski•Oct 8, 2015                                        

Some times browsers send OPTIONS request... you will need to handle csrf protection and origin (if you work on different domains). I have implemented AngularJS as GUI and Laravel as API and work like a charm... but, yes... for production please user SSL

                           
jartaud                                
Level 2                                
jartaud•Nov 12, 2015                                    

L5.1 will redirect after successfull login. So in case you want to prevent this behaviour, you'll have to override handleUserWasAuthenticated method from AuthenticatesUsers trait.

`` protected function handleUserWasAuthenticated(Request $request, $throttles) { if ($throttles) { $this ->clearLoginAttempts($request); }

    if (method_exists($this, 'authenticated')) {
        return $this ->authenticated($request, Auth::user());
    }
    if ($request->ajax()) {
           return response()->json([
               'intended' => \URL::previous()
           ]);
    } else {
        return redirect()->intended($this->redirectPath());
    }
}
                                   

`

4                                    
                               
ahmed-aliraqi                                
Level 1                                
ahmed-aliraqi•May 12, 2017                                    

Override this method in your LoginController to login by ajax :)

/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(\Illuminate\Http\Request $request, $user)
{
    if ($request->ajax()){

        return response()->json([
            'auth' => auth()->check(),
            'user' => $user,
            'intended' => $this->redirectPath(),
        ]);

    }
}
                               
5                                    
                               
huuvan20                                
Level 4                                
huuvan20•Dec 3, 2017                                        

@ahmed-aliraqi This works, thank you!

1                                    
                               
varuninorbit                                
Level 1                                
varuninorbit•Jan 26                                    

@JLRDW - What difference Ajax makes in sending the secure information?

It is ok if it is sent to a https url.

                           

Please sign in or create an account to participate in this conversation.

1 of 12 repliesJul 5, 2015                

来自   https://laracasts.com/discuss/channels/requests/laravel-login-with-ajax



spicydog/laravel-ajax-login-example        

 Code Issues 0 Pull requests 0 Projects 0 Security Insights    

All your code in one place

Over 40 million developers use GitHub together to host and review code, project manage, and build software together across more than 100 million projects.

Sign up for free See pricing for teams and enterprises            
Solution for https://stackoverflow.com/questions/40357637/login-register-api-with-laravel-5            
  •  7 commits

  •  1 branch

  •  0 releases

  •  1 contributor

PHPHTMLVue                
Branch: master 
Find File            
Clone or download                 
@spicydog                
spicydog Update npm package versions            
Latest commita26932bon 30 May            
Type                        Name                        Latest commit message                        Commit time                        

app                        Use redirect path from Laravel                        2 years ago                        

bootstrap                        Initial commit                        2 years ago                        

config                        Initial commit                        2 years ago                        

database                        Initial commit                        2 years ago                        

public                        Initial commit                        2 years ago                        

resources                        Use redirect path from Laravel                        2 years ago                        

routes                        Initial commit                        2 years ago                        

storage                        Initial commit                        2 years ago                        

tests                        Initial commit                        2 years ago                        

.env.example                        Initial commit                        2 years ago                        

.gitattributes                        Initial commit                        2 years ago                        

.gitignore                        Initial commit                        2 years ago                        

artisan                        Initial commit                        2 years ago                        

composer.json                        Initial commit                        2 years ago                        

composer.lock                        Initial commit                        2 years ago                        

package.json                        Update npm package versions                        3 months ago                        

phpunit.xml                        Initial commit                        2 years ago                        

readme.md                        Initial commit                        2 years ago                        

server.php                        Initial commit                        2 years ago                        

webpack.mix.js                        Initial commit                        2 years ago                        

 readme.md

                   

Build Status Total Downloads Latest Stable Version License                    

About Laravel

Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as:

  • Simple, fast routing engine.

  • Powerful dependency injection container.

  • Multiple back-ends for session and cache storage.

  • Expressive, intuitive database ORM.

  • Database agnostic schema migrations.

  • Robust background job processing.

  • Real-time event broadcasting.

Laravel is accessible, yet powerful, providing tools needed for large, robust applications. A superb combination of simplicity, elegance, and innovation give you tools you need to build any application with which you are tasked.

Learning Laravel

Laravel has the most extensive and thorough documentation and video tutorial library of any modern web application framework. The Laravel documentation is thorough, complete, and makes it a breeze to get started learning the framework.

If you're not in the mood to read, Laracasts contains over 900 video tutorials on a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library.

Laravel Sponsors

We would like to extend our thanks to the following sponsors for helping fund on-going Laravel development. If you are interested in becoming a sponsor, please visit the Laravel Patreon page:

  • Vehikl

  • Tighten Co.

  • British Software Development

  • Styde

  • Fragrantica

  • SOFTonSOFA

  • User10

  • Soumettre.fr

Contributing

Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the Laravel documentation.

Security Vulnerabilities

If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.

License

The Laravel framework is open-sourced software licensed under the MIT license.


来自  https://github.com/spicydog/laravel-ajax-login-example

普通分类: 
laravel
Powered by Drupal

友情链接

校园好文网

 www.shipingzhong.cn  个人技术网_前端_后台    备案号:苏ICP备18010659号-2