Wes Murray Wes Murray - 1 month ago 7
AngularJS Question

Laravel with AngularJS Login

Im using Laravel 5.3 as an API and i have AngularJS running my frontend.
I have built the login portion of the backend that accepts the form data and responds with a json object.

My question is when i recieve the success object from the api to say that the login details are sucessfull. How do i use AngularJS to then login the user from the frontend.

AuthenticateUser.php


http://pastebin.com/PZqGCpz5


app.js

var app = angular.module('app', []);

app.controller('AppCtrl', function($scope, $http) {

$scope.login = {};

$scope.submitLoginForm = function () {

var email = $scope.login.email;
var password = $scope.login.password;

$http({
method : 'POST',
url : '/api/1.0/auth/login',
data : { email, password },
headers : { 'Content-Type': 'application/json' }
})
.success(function(data) {
console.log(data);
});
}
}


JSON Response

success: Object
message : authentication_successfull
code : 200
user_id : 1


What steps should i take from here to log the user into the frontend.

Thanks in advance

Answer

You can do this with the help of api_token approach.

First when you call a login api then create a unique token specific to user and save it database and send it in response as:

success: Object
   message : authentication_successfull
   code    : 200
   data : {api_token: some_random_key}

Then for subsequent request send that api_token in the request headers. And server will automatically logins the user if you are using the auth:api middleware as:

Route::group(['middleware' => ['auth:api']], function() 
{
    // API routes here
});

For reference