πŸš€ DevOps & SRE Certification Program πŸ“… Starting: 1st of Every Month 🀝 +91 8409492687 πŸ” Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Create Rest API with Laravel Passport Authentication

Laravel passport

Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use. We will use laravel passport to authenticate token-based request except for session

You have to just follow a few steps to get following web services:

  • Login API
  • Register API
  • Details API

Step 1 – First Create a Project

$ composer create-project --prefer-dist laravel/laravel RestAPI "5.8.*"

Step 2 – Install Package

There are two ways to install package:

  1. Write the following command given below
composer require laravel/passport

2. Update the composer and check your composer.json file

composer update

Step 3 – Open config/app.php file and add service provider

config/app.php
'providers' =>[
Laravel\Passport\PassportServiceProvider::class,
],
view raw app.php hosted with ❀ by GitHub

Step 4 – Update database name (.env file)

Step 5 – Open phpMyAdmin and create databse

Step 5 – Run Migration and Install

php artisan migrate

php artisan passport:install

Step – 6 Modify User.php

Go to app–>http–>User.php

Step – 7 Modify app/Providers/AuthServiceProvider.php

Step 8 – Modify config/auth.php

<?php
return [
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
view raw auth.php hosted with ❀ by GitHub

Step -9 Create API Route

Go to routes–>api.php

Route::post('login', 'API\UserController@login');
Route::post('register', 'API\UserController@register');
Route::get('user', 'API\UserController@getAllUsers');
Route::group(['middleware' => 'auth:api'], function()
{
Route::get('details', 'API\UserController@details');
});
Route::put('update/{id}','API\UserController@update');
Route::delete('delete/{id}','API\UserController@delete');
view raw api.php hosted with ❀ by GitHub

Step 10 – Create The Controller

 php artisan make:controller UserController

Step 11 – Open UserController

  • We create an API folder inside the Controllers folder
  • After Creating, we Move UserController.php to API folder
<?php
namespace App\Http\Controllers;
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
class UserController extends Controller
{
public $successStatus = 200;
/**
* login api
*
* @return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
// Register api, We are registering the user details
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['name'] = $user->name;
return response()->json(['success'=>$success], $this-> successStatus);
}
// we are creating the update funtion, to update the user details
public function update(Request $request)
{
$res=User::find($request->id);
$res->name=$request->name;
$res->email=$request->email;
$res->password= bcrypt($request['password']);
$result=$res->save();
if($result)
{
return ["result"=>"data is updated"];
}
else
{
return ["result"=>"Operation Failed , data is not updated"];
}
}
//Get all the details of the users
public function getAllUsers()
{
$user = User::get()->toJson(JSON_PRETTY_PRINT);
return response($user, 200);
}
// Get the currently authenticated user...
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this-> successStatus);
}
// Delete the records from the database table
public function delete($id) {
if(User::where('id', $id)->exists()) {
$user = User::find($id);
$user->delete();
return response()->json([
"message" => "records deleted"
], 202);
}
else
{
return response()->json([
"message" => "user not found"
], 404);
}
}
}

Go and Run the server inside RestAPI folder, code is given below-

$php artisan serve

Step – 12 Download the app to quickly get started using the Postman API Platform. 

Step – 13 After Installing, Open and Hit the API

We have to write key-value pair to store data in database. Given Below

Now, Token is generated in the above image by hitting the send button. After hitting the send button the key-value pair is stored in the database. Let’s go and open phpMyAdmin given below.

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.