Passport Authentication

We will learn to how to setup Signup, Login and Logout

Step 1: Create Controller

Create new controller inHttp/Controllers/AuthController.php by the following command:

php artisan make:controller AuthController

And put below code:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;
use DB;
use Validator;

class AuthController extends Controller
{
  private $successStatus = ['api_status' =>1 ,'code' => 200,];
  private $wrongHTTP = ['response'=>['api_status'=>0,'code'=>400,
  'message'=>'Your HTTP method is not correct']];
    
  public function signup(Request $request)
  {
     if($request->isMethod('post'))
     {$validator = Validator::make($request->all(), [ 
                        'name' => 'required', 
                        'email' => 'required|email', 
                        'password' => 'required', 
                        ]);
      if ($validator->fails()) {        
            return response()->json(['response'=>[
                                'code'=>400,
                                'api_status'=>0,
                                'message'=>'Data is not in the 
                                 proper format',]]);        
            }
       $email = $request->email;
       $eid =DB::table('users')->where('email' , $email)->exists();
       if($eid == true)
       {
       return response()->json(['response'=>[
                      'api_status' => 0 ,
                      'code' => 400,
                      'message'=> 'This email already exist'
                    ]],400);
            }
       else
       {
        $input = $request->all(); 
        $input['password'] = bcrypt($input['password']); 
        $user = User::create($input);
        $token =  $user->createToken('Personal Access Token')-> accessToken; 
        $name =  $user->name;
        $email = $user->email;
        return response()->json(['response' => [
                      'api_status'=>1,
                      'code'=>201,
                      'message' => 'Successfully registered',
                      ]
              ],201); 
            }
        }
            return response()->json($this -> wrongHTTP, 400);
    }
}

Step 2: Create Route

Open api.php from routes folder , and replace the code of route with the following

Route::group([
    'prefix' => 'auth',
], function () {
    Route::any('signup', 'AuthController@signup');
});

Step 3: Run API

Now we are ready to run our API so run below command to quick run:

php artisan serve

you will get an url something like this http://localhost:8000 or http://127.0.0.1:8000

Step 4: Test API

To test the API, use a tool called Postman, you may have different IP and port number and after the port number, you should use this /api/auth/signup

NOTE: If you want to Interact with this api from the frontend (i.e. vuejs), then you need to follow the below steps

Step 5: Set the URL

  1. From 2nd step you will get an URL which looks something like this http://localhost:8000 or http://127.0.0.1:8000

  2. Create a webServices folder at location resources/js/

  3. Create a file named index.js

  4. Then you have to place this http://127.0.0.1:8000 url in resources/js/webServices/index.js rest of the parameters will remain same.

import axios from 'axios';

let webService = axios.create({
    baseURL: 'http://127.0.0.1:8000/api/auth'
});

export default webService;

5. For signup with laravel-passport, Go to location resources->js->views->session->SignUpOne.vue and add the sign up with laravel passport as shown in screenshot:

6. For login with laravel-passport, Go to location resources->js->views->session->LoginOne.vue and add the login with laravel passport button as mentioned in screenshot.

7. Call the signupWithLaravel method as you have defined on the button click in the SignUpOne.vue file and write following lines of code .

SignUpOne.vue
 signupWithLaravel() {
    let userDetail = {
      name: this.name,
      email: this.email,
      password: this.password
    };
	this.$store.dispatch("signupUserWithLaravelPassport", {
	  userDetail
	});
  },
  signInWithFacebook() {
    this.$store.dispatch("signinUserWithFacebook", {
    router: this.$router
  });
  ...

8. Call the signInwithLaravelPassport method as you have defined on the button click in the LoginOne.vue file and write following lines of code .

LoginOne.vue
signInWithLaravelPassport(){
			 const user = {
        email: this.email,
        password: this.password
      };
      this.$store.dispatch("signInWithLaravelPassport", {
        user
      });
	},
    signInWithFacebook() {
      this.$store.dispatch("signinUserWithFacebook");
    },
    ...

9. Next, Go to location resources->js->store->modules->auth->index.js and add the following lines of code under action .

index.js
// actions
const actions = {
    signupUserWithLaravelPassport(context, payload){
        webServices.post('/signup', JSON.stringify(payload.userDetail),{ headers: {'Content-Type':'application/json'}})
      	.then(response => {
				if(response.data.response.api_status){
					context.commit('signUpUser');
					Nprogress.done();
					setTimeout(() => {
						context.commit('signUpUserSuccess', payload);
					}, 500);
				}else{
					context.commit('signUpUserFailure', response.data.response);
				}
        })
        .catch(error => {
            console.log(error);
            console.log("Failed");
        })           
    },
	 signInWithLaravelPassport(context, payload){
	 	const { user } = payload;
    	context.commit('loginUser');
		webServices.post('/login', JSON.stringify(user), { headers: {'Content-Type':'application/json'}})
			.then(response => {
				if(response.data.response.api_status){
					Nprogress.done();
					setTimeout(() => {
						context.commit('loginUserSuccess', user);
					}, 500);
				}else{
					context.commit('loginUserFailure', response.data.response);
				}
        })
        .catch(error => {
            console.log(error);
            console.log("Failed");
        })
	 },
	...
}

10. Then import the following line in the resources/js/store/modules/auth/index.js import webServices from 'WebServices As described in screenshot:

11.Then open the webpack.mix.js file from your root directory and add the following line under mix.webpackConfig as shown in screenshot

'WebServices': path.resolve(__dirname, 'resources/js/webServices/'),

After doing above steps, run command npm run dev to compile the all the project files and then run php artisan serve command to run the project.

Note: To test the login or signup functionality, first you need to start mysql to interact with database from your local server. For E.g xampp.

Last updated