Hello buddies,
Today,I will learn you how to use sanctum api authenticationin laravel 8. We will Show example of sanctum api authentication in laravel 8. It’s a small example of a sanctum in Laravel 8. You’ll learn how to use the sanctum rest api in Laravel 8. So, let’s make an example of laravel 8 sanctum api token tutorial by following a few steps.
Create Laravel project
composer create-project --prefer-dist laravel/laravel blog
Set Database Configuration properties
Go to the .env file and set you Database name, Database username and password.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelblog
DB_USERNAME=root
DB_PASSWORD=
Install Laravel sanctum
We need to install sanctum via the Composer package manager, so one your terminal and fire bellow command.
composer require laravel/sanctum
After successfully install package, we need to publish configuration file with following command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Now Migrate Database
php artisan migrate
Next, we need to add middleware for sanctum api, so let’s add as like bellow:
app/Http/Kernel.php
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
],
Sanctum Configuration
In this step, we have to configuration on three place model, service provider and auth config file. So you have to just following change on that file.
In model we added HasApiTokens class of Sanctum,
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\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable,HasApiTokens;
/**
* 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',
];
}
Add Post Table and Model
In the terminal crate Post Model and migration file
php artisan make:model Post -m
app/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title', 'detail'
];
}
database/migrations/2021_06_14_104646_post_tabel.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class PostTabel extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('detail');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
After create migration we need to run above migration by following command:
php artisan migrate
Create API Routes
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
use App\Http\Controllers\RegisterController;
/*
|--------------------------------------------------------------------------
| 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:sanctum')->group( function () {
Route::resource('posts', PostController::class);
});
Create Controllers
We have to create 1) BaseController, 2) PostController and 3) RegisterCoontroller. So, let’s start
php artisan make:controller BaseController
php artisan make:controller PostController
php artisan make:controller RegisterController
app/Http/Controllers/BaseController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
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/PosteController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController as BaseController;
use App\Models\Post;
use Validator;
use App\Http\Resources\Post as PostResource;
class PostController extends BaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return $this->sendResponse(PostResource::collection($posts), 'posts 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',
'detail' => 'required'
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$post = Post::create($input);
return $this->sendResponse(new PostResource($post), 'post created successfully.');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
if (is_null($post)) {
return $this->sendError('post not found.');
}
return $this->sendResponse(new PostResource($post), 'post 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, Post $post)
{
$input = $request->all();
$validator = Validator::make($input, [
'title' => 'required',
'detail' => 'required'
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$post->title = $input['title'];
$post->detail = $input['detail'];
$post->save();
return $this->sendResponse(new PostResource($post), 'post updated successfully.');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
return $this->sendResponse([], 'post deleted successfully.');
}
}
app/Http/Controllers/RegisterController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\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',
'c_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')->plainTextToken;
$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('MyApp')->plainTextToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
}
Create Eloquent API Resources
This is a very important step of creating rest api in laravel 8. you can use eloquent api resources. it will helps you to make same response layout of your model object. we used in PostController file. now we have to create it using following command.
php artisan make:resource Post
Now there created new file with new folder on following path:
app/Http/Resources/Post.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Post 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,
'detail' => $this->detail,
'created_at' => $this->created_at->format('d/m/Y'),
'updated_at' => $this->updated_at->format('d/m/Y'),
];
}
}
Now we are ready to to run full restful api and also passport api in laravel. so let’s run our example so run bellow command for quick run:
php artisan serve
make sure in details api we will use following headers as listed bellow:
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
Now simply you can run bellow listed url like as bellow:
1) Register API: Method: POST, URL:http://localhost:8000/api/register
2) Login API: Metho: POST, URL:http://localhost:8000/api/login
3) Store API: Method: POST, URL:http://localhost:8000/api/posts
4) Get all Post API: Method: GET, URL:http://localhost:8000/api/posts
5) Get Single Post API: Method: GET, URL:http://localhost:8000/api/posts/{id}
6) Update Single Post API: Method: PUT, URL:http://localhost:8000/api/posts/{id}
7) Delete Single Post API: Method: DELETE, URL:http://localhost:8000/api/posts/{id}
Some ss:
Hope it helps you!