Laravel 8

Laravel 8 REST API Authentication with Passport

Pinterest LinkedIn Tumblr

Laravel 8 API authentication with passport tutorial. In this tutorial, I will show you how to build rest APIs with passport authentication in Laravel 8.

Also, I will show you how to install passport and configure passport in laravel 8 app.

First of all, you need to follow this step.

Laravel 8 API Authentication with Passport Tutorial

Step 1: Install laravel 8 App
Step 2: Database Configuration in .env file
Step 3: Install Passport Auth
Step 4: Passport Configuration
Step 5: Run Migration
Step 6: Create APIs Route
Step 7: Create Passport Auth Controller

Step 8: Create Eloquent API Resources
Step 9: Now Test Laravel REST API in Postman

Step 1: Install laravel 8 App

We need to run command to create Laravel 8 projects.

composer create-project --prefer-dist laravel/laravel laravel-8-passport-api
cd laravel-8-passport-api

Step 2 : Connecting App to Database

Next step, we will set the database credentials in the application. Let’s open your project .env file and set the database credentials here.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelAPI
DB_USERNAME=root
[email protected]

Generate barcode in laravel: https://therealprogrammer.com/how-to-generate-barcode-in-laravel-8/

Step 3: Install Passport Auth

php artisan passport:install

Step 4: Passport Configuration

In this step, I will configuration on three place model, service provider and auth config file. So we need change in following file.

In model we added HasApiTokens class of Passport,

In auth.php, we added api auth configuration.

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;


class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

config/auth.php

<?php

return [

/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/

'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],


/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/

'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],

'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],


/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/

'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],

// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],

/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/

'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],

/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/

'password_timeout' => 10800,

];

Step 5: Run Migration

Here I will run create migration for blogs table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:migration create_blogs_table

After this command I will open file in following path database/migrations and I will put bellow code in your migration file for create blogs table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}

Now, Run migrate command.

php artisan migrate

Add in model

app/Models/Blog.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
use HasFactory;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'description'
];
}

Step 6: Create API Routes

In this step, I will create api routes. Laravel provide api.php file for write web services route. So, let’s add new route on that file.

routes/api.php

<?php


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\API\RegisterController;
use App\Http\Controllers\API\ProductController;
use App\Http\Controllers\API\BlogController;
  
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
  
Route::post('register', [RegisterController::class, 'register']);
Route::post('login', [RegisterController::class, 'login']);


Route::middleware('auth:api')->group( function () {
    Route::resource('blogs', BlogController::class);
});

Step 7: Create Passport Auth Controller

app/Http/Controllers/API/BaseController.php

<?php


namespace App\Http\Controllers\API;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;


class BaseController extends Controller
{
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];


return response()->json($response, 200);
}


/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];


if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}


return response()->json($response, $code);
}
}

app/Http/Controllers/API/RegisterController.php

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;

class RegisterController extends BaseController
{
/**
* Register api
*
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'confirm_password' => 'required|same:password',
]);

if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}

$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;

return $this->sendResponse($success, 'User register successfully.');
}

/**
* Login api
*
* @return \Illuminate\Http\Response
*/
public function login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::user();
$success['token'] = $user->createToken('My Token')-> accessToken;
$success['name'] = $user->name;

return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
}

app/Http/Controllers/API/BlogController.php

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\Blog;
use Validator;
use App\Http\Resources\Blog as BlogResource;

class BlogController extends BaseController
{


/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$Blogs = Blog::all();
return $this->sendResponse(BlogResource::collection($Blogs), 'Blogs retrieved successfully.');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();

$validator = Validator::make($input, [
'title' => 'required',
'description' => 'required'
]);

if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}

$Blog = Blog::create($input);

return $this->sendResponse(new BlogResource($Blog), 'Blog created successfully.');
}

/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{


$Blog = Blog::find($id);

if (is_null($Blog)) {
return $this->sendError('Blog not found.');
}

return $this->sendResponse(new BlogResource($Blog), 'Blog retrieved successfully.');
}

/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Blog $blog)
{

$input = $request->all();

$validator = Validator::make($input, [
'title' => 'required',
'description' => 'required'
]);

if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}

$blog->title = $input['title'];
$blog->description = $input['description'];
$blog->save();

return $this->sendResponse(new BlogResource($blog), 'Blog updated successfully.');
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Blog $blog)
{
$blog->delete();
return $this->sendResponse([], 'Blog deleted successfully.');
}
}

Step 8: Create Eloquent API Resources

php artisan make:resource Blog

app/Http/Resources/Blog.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Blog extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'created_at' => $this->created_at->format('d/m/Y'),
'updated_at' => $this->updated_at->format('d/m/Y'),
];
}
}

Step 9: Now Test Laravel REST API in Postman

Don’t forget to implement following details.

'headers' => [

    'Accept' => 'application/json',

    'Authorization' => 'Bearer '.$accessToken,

]

Now check Routes in below.

post: http://127.0.0.1:8000/api/register


post: http://127.0.0.1:8000/api/login

get: http://127.0.0.1:8000/api/blogs


post: http://127.0.0.1:8000/api/blogs


put: http://127.0.0.1:8000/api/blogs/1


delete: http://127.0.0.1:8000/api/blogs/1

Git: https://github.com/siddharth018/Laravel-8-REST-API-with-Passport-Authentication

Write A Comment

Faster PHP Cloud Hosting