# Passport Authentication

### **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`

![](/files/-LZsmzwftQX4ckXOCEC6)

**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](/files/-LZsn_rDmE9guaT5Pm88)

&#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](/files/-LZsnqUnZyEp-E78EEFP)

&#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](/files/-LZt4fbl9wdQ5PESbvHp)

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](/files/-LZt5Tou7OYwaG9BzBrx)

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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://iron-network.gitbook.io/vuely/vuely-laravel-with-api-authentication/passport-authentication.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
