> For the complete documentation index, see [llms.txt](https://iron-network.gitbook.io/vuely/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://iron-network.gitbook.io/vuely/vuely-laravel-with-api-authentication/passport-authentication.md).

# Passport Authentication

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

### **Step 1: Create Controller** <a href="#step-1-create-controller" id="step-1-create-controller"></a>

Create new controller in`Http/Controllers/AuthController.php` by the following command:

```
php artisan make:controller AuthController
```

And put below code:

```php
<?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 <a href="#step-2-create-route" id="step-2-create-route"></a>

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

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

### **Step 3: Run API** <a href="#step-3-run-api" id="step-3-run-api"></a>

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** <a href="#step-4-test-api" id="step-4-test-api"></a>

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`

![](https://2330000780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LF1B-IA07NduZLLz_4Z%2F-LZsmu5vDuCYBCO0a-ty%2F-LZsmzwftQX4ckXOCEC6%2Fassets--LF1B-IA07NduZLLz_4Z--LRtjY4q6uh2ha6xw9Gf--LRvKQl4vThK8EGbAaJT-Screenshot%20from%202018-11-22%2017-41-51.png?alt=media\&token=9ca6de75-f07e-4040-a236-75011c347510)

**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 <a href="#step-5-set-the-url" id="step-5-set-the-url"></a>

1. From 2nd step you will get an URL which looks something like this `http://localhost:8000` or `http://127.0.0.1:8000`&#x20;
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.

```javascript
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: &#x20;

![SignUpOne.vue](https://2330000780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LF1B-IA07NduZLLz_4Z%2F-LZsmu5vDuCYBCO0a-ty%2F-LZsn_rDmE9guaT5Pm88%2Fassets--LF1B-IA07NduZLLz_4Z--LWUZ1_SxQI2JtrTahtw--LWUn2FmX8vanfnwwuPN-Signup.png?alt=media\&token=71a78e3c-791c-4d03-86c1-9241bc86c280)

&#x20;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.

![LoginOne.vue](https://2330000780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LF1B-IA07NduZLLz_4Z%2F-LZsmu5vDuCYBCO0a-ty%2F-LZsnqUnZyEp-E78EEFP%2Fassets--LF1B-IA07NduZLLz_4Z--LWUZ1_SxQI2JtrTahtw--LWUfGiLsU1lBqVLpLUC-PassportAuthentication.png?alt=media\&token=8685667a-9cf7-4b2a-8b0a-d36e2b278be4)

&#x20;7\. Call the `signupWithLaravel` method as you have defined on the button click in the `SignUpOne.vue` file and write following lines of code .

{% code title="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
  });
  ...
```

{% endcode %}

&#x20;8\. Call the `signInwithLaravelPassport` method as you have defined on the button click in the `LoginOne.vue` file and write following lines of code .

{% code title="LoginOne.vue" %}

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

{% endcode %}

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

{% code title="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");
        })
	 },
	...
}
```

{% endcode %}

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

![index.js](https://2330000780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LF1B-IA07NduZLLz_4Z%2F-LZt3t0KKhGG4PW5zKPr%2F-LZt4fbl9wdQ5PESbvHp%2Fpicturemessage_q4rulplg.guy.png?alt=media\&token=adb93b64-3ee4-47c6-a50f-98a36699e0db)

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/'),
```

![webpack.mix.js](https://2330000780-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LF1B-IA07NduZLLz_4Z%2F-LZt3t0KKhGG4PW5zKPr%2F-LZt5Tou7OYwaG9BzBrx%2Fqw.png?alt=media\&token=3e0eab4a-e4c9-4291-b426-99f16a9a0cd3)

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.
