In this tutorial, you’ll learn how to use Laravel Passport authentication in your Laravel application. We will also use Laravel Passport authentication to build a simple product (create, query, update, and delete).

Laravel already provides traditional login form authentication, but what if you want to use APIs? APIs use tokens to authenticate users because they do not use sessions. When a user logs in through the API, a token is generated and sent to the user, who can be used for authentication. Laravel provides the Passport with no difficulty in using API authentication.

Let’s look at how to set up and configure the Laravel Passport for API authentication and RESTful APIs in a Laravel application.

Create a new application

Let’s create a new Laravel application. Execute the following command to create a brand new Laravel application.

composer create-project --prefer-dist laravel/laravel passport
Copy the code

The installationPassportextension

We installed the Passport extension using Composer. Execute the following command to install the extension.

composer require laravel/passport
Copy the code

LaravelconfigurationPassport

The Laravel Passport extension requires some configuration.

Service provider

We used the latest version of Laravel 5.6, which can use package discovery and automatic registration of services. If you are using Laravel 5.4 or lower, you will need to register the Passport service in the config/app.php file. Add the registration service to the providers array in this file.

'providers' => [
    ....
    Laravel\Passport\PassportServiceProvider::class,
]
Copy the code

Migration and Installation

Set the database credentials in the **. Env ** file. Laravel Passport provides the migration files needed for the Passport tables in our database. The Passport migration is used to store token and client information. Run the migration command to migrate the schema to the database.

php artisan migrate
Copy the code

Next, you need to install Passport using the following command. It generates the encryption key needed to generate the secret access token.

php artisan passport:install
Copy the code

Passport configuration

In this step, we need to make changes in the Laravel application to complete the Passport configuration.

app/User.php

Add the Laravel\Passport\HasApiTokens trait to your User model. It will provide some helper methods.

<? php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; /** * this is a collection of assignable attributes ** @var array */ protected$fillable = [
        'name'.'email'.'password',]; /** * this is a collection of attributes that should be hidden ** @var array */ protected$hidden = [
        'password'.'remember_token',]; }Copy the code

AuthServiceProvider

Add the Passport :: Routes () method to the Bootstrap method of AuthServiceProvider. It will generate the necessary routes. This is app/will/AuthServiceProvider. PHP after the change.

<? php namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Laravel\Passport\Passport; class AuthServiceProvider extends ServiceProvider { /** * The policy mappingsfor the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model'= >'App\Policies\ModelPolicy',]; /** * Register any authentication / authorization services. * * @return void
     */
    public function boot()
    {
        $this->registerPolicies(); Passport::routes(); }}Copy the code

config/auth.php

In the config/auth.php file, set the driver to passport.

return[...'guards'= > ['web'= > ['driver'= >'session'.'provider'= >'users',].'api'= > ['driver'= >'passport'.'provider'= >'users',]],... ]Copy the code

Create routing

Let’s create an API route and add the route on routes/api.php.

Route::post('login'.'PassportController@login');
Route::post('register'.'PassportController@register');

Route::middleware('auth:api')->group(function () {
    Route::get('user'.'PassportController@details');

    Route::resource('products'.'ProductController');
});
Copy the code

Creating an Authentication Controller

Let’s set up the authentication logic. Create the Passport controller by running the following command.

php artisan make:controller PassportController
Copy the code

Copy the following code to Http/app/Controllers/PassportController. PHP

<? php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; class PassportController extends Controller { /** * Handles Registration Request * * @param Request$request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $this->validate($request['name'= >'required|min:3'.'email'= >'required|email|unique:users'.'password'= >'required|min:6',]);$user = User::create([
            'name'= >$request->name,
            'email'= >$request->email,
            'password' => bcrypt($request->password)
        ]);

        $token = $user->createToken('TutsForWeb')->accessToken;

        return response()->json(['token'= >$token], 200);
    }

    /**
     * Handles Login Request
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = [
            'email'= >$request->email,
            'password'= >$request->password
        ];

        if (auth()->attempt($credentials)) {
            $token = auth()->user()->createToken('TutsForWeb')->accessToken;
            return response()->json(['token'= >$token], 200);
        } else {
            return response()->json(['error'= >'UnAuthorised'], 401);
        }
    }

    /**
     * Returns Authenticated User Details
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function details()
    {
        return response()->json(['user'=> auth()->user()], 200); }}Copy the code

Let me explain the above code

In the Register method, we validate the request data and then create the user. We create the token using the createToken method and pass the name as a parameter. Finally, we return the token in the JSON response.

In the Login method, we try to authenticate with request parameters. The appropriate response is then returned based on the success or failure of the attempt.

In the Details method we just return the user model.

Create the product CRUD

Let’s create a CRUD for the product. Run the following commands to generate product models, migrate files, and controllers.

php artisan make:model Product -mc
Copy the code

It will create a new database migration file create_products_table.php in the database/migrations folder. Update the up method to the following code.

public function up()
{
    Schema::create('products'.function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->string('name');
        $table->integer('price');
        $table->timestamps();

        $table->foreign('user_id')
            ->references('id')
            ->on('users');
    });
}
Copy the code

Now add the fillable attribute to the Product model. Open the product.php file in the app folder.

<? php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected$fillable = [
        'name'.'price'
    ];
}
Copy the code

Now we run the data migration.

php artisan migrate
Copy the code

Now, let’s add the association method to the app/ user.php file.

public function products()
{
    return $this->hasMany(Product::class);
}
Copy the code

Open the productController.php file in app/Http/Controllers. Copy the following code into the production controller.

<? php namespace App\Http\Controllers; use App\Product; use Illuminate\Http\Request; class ProductController extends Controller { publicfunction index()
    {
        $products = auth()->user()->products;

        return response()->json([
            'success'= >true.'data'= >$products
        ]);
    }

    public function show($id)
    {
        $product = auth()->user()->products()->find($id);

        if (!$product) {
            return response()->json([
                'success'= >false.'message'= >'Product with id ' . $id . ' not found'
            ], 400);
        }

        return response()->json([
            'success'= >true.'data'= >$product->toArray()
        ], 400);
    }

    public function store(Request $request)
    {
        $this->validate($request['name'= >'required'.'price'= >'required|integer'
        ]);

        $product = new Product();
        $product->name = $request->name;
        $product->price = $request->price;

        if (auth()->user()->products()->save($product))
            return response()->json([
                'success'= >true.'data'= >$product->toArray()
            ]);
        else
            return response()->json([
                'success'= >false.'message'= >'Product could not be added'
            ], 500);
    }

    public function update(Request $request.$id)
    {
        $product = auth()->user()->products()->find($id);

        if (!$product) {
            return response()->json([
                'success'= >false.'message'= >'Product with id ' . $id . ' not found'
            ], 400);
        }

        $updated = $product->fill($request->all())->save();

        if ($updated)
            return response()->json([
                'success'= >true
            ]);
        else
            return response()->json([
                'success'= >false.'message'= >'Product could not be updated'
            ], 500);
    }

    public function destroy($id)
    {
        $product = auth()->user()->products()->find($id);

        if (!$product) {
            return response()->json([
                'success'= >false.'message'= >'Product with id ' . $id . ' not found'
            ], 400);
        }

        if ($product->delete()) {
            return response()->json([
                'success'= >true
            ]);
        } else {
            return response()->json([
                'success'= >false.'message'= >'Product could not be deleted'], 500); }}}Copy the code

test

Now that our logic is complete, let’s start testing. We’ll test it on a PHP development server, but you can use virtual hosts as needed. Run the following command to serve the application on the PHP development server.

php artisan serve
Copy the code

Now let’s test our API Postman with a test tool.

Registered interface

Login interface

Details of the interface

When testing the verbose interface or any API that requires user authentication, you need to specify two header request headers. You must specify tokens as Bearer tokens in the Authorization request header. Basically, you have to spell the tokens you receive after being logged in and registered as Bearer with a blank space.

'headers'= > ['Accept'= >'application/json'.'Authorization'= >'Bearer '. $accessToken,]Copy the code

Product List interface

Product Add Interface

Product Display interface

Product Update Interface

Product Deletion Interface

The complete code for this tutorial is available from Github

Article from: learnku.com/laravel/t/2… More articles: learnku.com/laravel/c/t…