TUTORIAL MEMBUAT RESTFUL API DENGAN SLIM FRAMEWORK [BAGIAN 5]

TUTORIAL MEMBUAT RESTFUL API DENGAN SLIM FRAMEWORK [BAGIAN 5]

Assalamualaikum

Pada bagian 4 kita sudah bisa menampilkan data

TUTORIAL MEMBUAT RESTFUL API DENGAN SLIM FRAMEWORK [BAGIAN 4]

Sekarang kita akan membuat update data, lanjutkan file index.php

$app->post('/editcatatan/{id}', function($request, $response, $args) use($app, $db){

    $q = $db->tb_catatan()->where('id', $args);

    if($q->fetch()){

        $param = $request->getParams();
        $r = $q->update($param);
        echo json_encode(array(
            "error" => false,
            "message" => "Catatan berhasil diupdate"));

    }else{

        echo json_encode(array(
            "error" => true,
            "message" => "Catatan tersebut tidak ada"));

    }
});

 

Berikut Kode Lengkapnya

<?php 
require __DIR__ . '/vendor/autoload.php';
require 'libs/NotORM.php'; 

use \Slim\App;

$app = new App();

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'dbcatatan';
$dbmethod = 'mysql:dbname=';

$dsn = $dbmethod.$dbname;
$pdo = new PDO($dsn, $dbuser, $dbpass);
$db  = new NotORM($pdo);

$app-> get('/', function(){
    echo "API Catatan Keuangan With SLIM Framework";
});

$app->post('/addcatatan', function($request, $response, $args) use($app, $db){
    $param = $request->getParams();
    $r = $db->tb_catatan->insert($param);

    $res["error"] = false;
    $res["message"] = "Berhasil menambahkan catatan ke database";
    echo json_encode($res);
});

$app ->get('/listcatatan', function() use($app, $db){

 $res["error"] = false;
    $res["message"] = "Berhasil mendapatkan data Catatan";

    foreach($db->v_catatan()->where('status', 0) as $data){
        $res['data'][] = array(
            'id' => $data['id'],
            'judul' => $data['judul'],
            'catatan' => $data['catatan'],
            'create_at' => $data['create_at'],
            'update_at' => $data['update_at']
            );
    }

    echo json_encode($res);

});

$app->post('/editcatatan/{id}', function($request, $response, $args) use($app, $db){

    $q = $db->tb_catatan()->where('id', $args);

    if($q->fetch()){

        $param = $request->getParams();
        $r = $q->update($param);
        echo json_encode(array(
            "error" => false,
            "message" => "Catatan berhasil diupdate"));

    }else{

        echo json_encode(array(
            "error" => true,
            "message" => "Catatan tersebut tidak ada"));

    }
});



$app->run();

 

Mari Kita Coba di Post Man, cek terlebih dahulu id yang mau diubah

localhost/apicatatan/index.php/listcatatan

jalankan update data

localhost/apicatatan/index.php/editcatatan/1

Sekarang kita cek di database

Tabel : tb_catatan
Tabel : tb_catatan_log

Semoga bermanfaat

Flutter Developer