Membuat Rest API Lebih Aman Di Laravel Framework - CRUDPRO

Membuat Rest API Lebih Aman Di Laravel Framework

Membuat Rest API Lebih Aman Di Laravel Framework

Hari ini saya akan menjelaskan cara membuat REST API di Laravel 9. Di video kali ini saya akan menjelaskan Operasi CRUD menggunakan REST API.

Langkah 1

Buat Postingan Model dengan migrasi.

php artisan make:model Post -m

Next Update File Migration di folder database/migrations.

<?php

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

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

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

Selanjutnya perbarui properti Model yang dapat diisi di 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', 'description'];
}
Langkah 2

Sekarang Hasilkan pengontrol dengan menjalankan perintah

php artisan make:controller Api\\PostController --model=Post

perintah ini akan menghasilkan file di app/Http/Controllers/Api/PostController.php Buka file dan perbarui kode di bawah ini.

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostRequest;
use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::all();

return response()->json([
            'status' => true,
            'posts' => $posts
        ]);
    }

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

 /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StorePostRequest $request)
    {
        $post = Post::create($request->all());

return response()->json([
            'status' => true,
            'message' => "Post Created successfully!",
            'post' => $post
        ], 200);
    }

/**
     * Display the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        //
    }

/**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function edit(Post $post)
    {
        //
    }

/**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(StorePostRequest $request, Post $post)
    {
        $post->update($request->all());return response()->json([
            'status' => true,
            'message' => "Post Updated successfully!",
            'post' => $post
        ], 200);
    }

/**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();

return response()->json([
            'status' => true,
            'message' => "Post Deleted successfully!",
        ], 200);
    }
}
Langkah — 3

Sekarang mari kita buat permintaan untuk memvalidasi data dengan menjalankan perintah di bawah ini.

php artisan make:request StorePostRequest

Sekarang buka file app/Http/Requests/StorePostRequest.php dan perbarui kode di bawah ini.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

/**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            "title" => "required|max:70",
            "description" => "required"
        ];
    }
}
Langkah — 4

Sekarang buat rute API di route/api.php

<?php

use App\Http\Controllers\Api\PostController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::apiResource('posts', PostController::class);

Sekarang layani aplikasi dan buka URL di tukang pos. Hasilnya akan terlihat seperti ini.

Membuat Rest API Lebih Aman Di Laravel Framework
Membuat Rest API Lebih Aman Di Laravel Framework
Membuat Rest API Lebih Aman Di Laravel Framework
Membuat Rest API Lebih Aman Di Laravel Framework

Membuat REST API AUTHENTICATION di LARAVEL 9 MENGGUNAKAN LARAVEL SANCTUM

Laravel Sanctum menyediakan sistem otentikasi kelas bulu untuk SPA (aplikasi satu halaman), aplikasi seluler, dan API sederhana berbasis token.

Langkah-langkah Instalasi

Jika Anda tidak menggunakan LARAVEL 9, Anda perlu menginstal LARAVEL Sanctum. Jika tidak, Anda dapat melewati langkah instalasi.

Langkah 1

Instal melalui komposer

composer require laravel/sanctum
Langkah 2

Publikasikan Penyedia Layanan Sanctum

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Langkah 3

Migrasi Basis Data

php artisan migrate

MENGGUNAKAN SANCTUM DI LARAVEL

Sifat
HasApiTokens
Pengguna di App\Models\User

Untuk menggunakan Sanctum, kita perlu menggunakan Kelas Sifat HasApiTokens di Model Pengguna. Model pengguna akan terlihat seperti ini.

Rute Otentikasi API

Buat AuthController untuk menangani semua otentikasi yang terkait dengan API

php artisan make:controller Api\\AuthController

Dalam file route\api.php perbarui API

Route::post('/auth/register', [AuthController::class, 'createUser']); Route::post('/auth/login', [AuthController::class, 'loginUser']);

Sekarang perbarui AuthContoller dengan

<?php

namespace App\Http\Controllers\Api;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{

/**
* Create User
* @param Request $request
* @return User
*/public function createUser(Request $request)
{

try {

//Validated$validateUser = Validator::make($request->all(),
[
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required'
]);

if($validateUser->fails()){
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}

$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);

return response()->json([
'status' => true,'message' => 'User Created Successfully',
'token' => $user->createToken("API TOKEN")->plainTextToken
], 200);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
/**

* Login The User
* @param Request $request
* @return User*
/public function loginUser(Request $request)
{
try {
$validateUser = Validator::make($request->all(),
[
'email' => 'required|email',
'password' => 'required'
]);
if($validateUser->fails()){
return response()->json([
'status' => false,
'message' => 'validation error',
'errors' => $validateUser->errors()
], 401);
}

if(!Auth::attempt($request->only(['email', 'password']))){
return response()->json([
'status' => false,
'message' => 'Email & Password does not match with our record.',
], 401);
}

$user = User::where('email', $request->email)->first();
return response()->json([
'status' => true,
'message' => 'User Logged In Successfully',
'token' => $user->createToken("API TOKEN")->plainTextToken
], 200);
}catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
}
Lindungi API Dengan Otentikasi kita perlu menggunakan auth:sanctum middleware.
Route::apiResource('posts', 
PostController::class)->middleware('auth:sanctum');

Berikut adalah hasilnya.

Membuat Rest API Lebih Aman Di Laravel Framework
Membuat Rest API Lebih Aman Di Laravel Framework
Membuat Rest API Lebih Aman Di Laravel Framework

Dalam tutorial ini, kita telah membahas membuat rest API lebih aman di laravel framework. Anda dapat menggunakan pengetahuan ini untuk membuat Rest API lebih aman.

Selamat mengkode!