arsitektur aplikasi monitor produksi konveksi

Membuat API users dan customer address dengan Framework Lumen | Bagian 3

Hallo geeker, bagaimana kabarnya ?

Pada kali ini saya akan membahas atau membuat service users dan penambahan services di artikel sebelum yaitu service customer address.

Goals :

  1. Users dan customers address ( create, update, read, delete )
  2. Custom index dan show

Membuat API Service

Untuk memulai pembahasan ini saya sarankan untuk mengikuti artikel sebelumnnya, karena ini berkelanjutan.

Service Users

Pertama kalian migration untuk membuat struktur column dengan mengetikan perintah

php artisan make:migration createUsersTable --table=users --create=users

Jika sudah, kalian buka file hasil migration, kemudian samakan kode berikut :

.....
public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('uid');
            $table->string('username')->nullable();
            $table->string('nickname')->nullable();
            $table->string('full_name')->nullable();
            $table->text('password')->nullable();
            $table->string('phone');
            $table->enum('gender', ['perempuan', 'pria']);
            $table->string('place_of_birth')->nullable();
            $table->date('date_of_birth')->nullable();
            $table->enum('level', ['customer', 'admin', 'employee']);
            $table->timestamps();
        });
    }
.....

Selanjutnya kalian buat model User.php di dalam folder app/models.

<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable, HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'uid', 'username', 'nickname', 'full_name', 'password', 'phone', 'gender', 'place_of_birth', 'date_of_birth', 'level'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    public function customersaddress()
    {
        return $this->hasMany(Customersaddress::class);
    }
}

Selanjutnya kalian membuat controllernya, UserController.php sebagai berikut :

<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseHelper;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Customersaddress;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    private $response;

    public function __construct(ResponseHelper $response)
    {
        $this->response = $response;
    }

    public function index(Request $request)
    {
        $user = User::latest();
        if ($request->name) {
            $user->search("$request->name");
        }
        $user = $user->paginate();
        return $this->response->successResponse($user);
    }
    
    public function show($user)
    {
        $user = User::with('customersaddress')->findOrFail($user);
        
        try {
            return $this->response->successResponse($user);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->response->unprocessableResponse($e);
        }
    }

    public function create(Request $request)
    {
        $this->validateRequest($request);
        $data = $request->all();
        try {
            ;
            DB::beginTransaction();
            $user = new User;
            $user->fill($data);
            $user->uid = '001-'.Carbon::now()->format('YmdHis');
            $user->save();
            DB::commit();

            return $this->response->successResponse($user);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->response->failedResponse($e);
        }
    }
    
    public function update(Request $request, $user)
    {
        $this->validate($request, [
            'username'  => 'string',
            'nickname'  => 'required',
            'full_name' => 'string',
            'password'  => 'string|password',
            'phone'     => 'required|numeric|digits_between:9,15',
            'gender'    => 'required',
            'level'     => 'required'
        ]);
        $data = $request->all();
        try {
            ;
            DB::beginTransaction();
            $user = User::findOrFail($user);
            $user->update($data);
            DB::commit();

            return $this->response->successResponse($user);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->response->failedResponse($e);
        }
    }

    public function destroy($user)
    {
        $user = User::findOrFail($user);
        
        $customerAddress = Customersaddress::where('user_id', $user->id)->first();
        $user->delete();
        $customerAddress->delete(); 

        return $this->response->successResponse([$user, $customerAddress]);
    }

    function validateRequest($request)
    {
        $this->validate($request, [
            'username'  => 'string|unique:users',
            'nickname'  => 'required',
            'full_name' => 'string',
            'password'  => 'string|password',
            'phone'     => 'required|numeric|digits_between:9,15',
            'gender'    => 'required',
            'level'     => 'required'
        ]);
    }
}

Nb: Dalam function create ada method ‘001-‘.Carbon::now()->format(‘YmdHis’) digunakan membedakan level user, jadi level ada 3 yaitu kode 001 untuk customer, kode 002 untuk admin, serta 003 untuk employee/karyawan. Kode create ini nanti juga perlu perubahan dalam pengecekan level usernya.

Kalau sudah , langkah selanjutnya membuat route user.php kemudian define didalam file bootstrap/app.php

Route route/user.php

<?php
$router->group(['prefix' => 'users'], function () use ($router) {
    $router->get('/', ['uses' => '[email protected]']);
    $router->get('/{user}', ['uses' => '[email protected]']);
    $router->post('/', ['uses' => '[email protected]']);
    $router->post('/{user}', ['uses' => '[email protected]']);
    $router->delete('/{user}', ['uses' => '[email protected]']);
});

Define route dengan menambahkan code didalam file bootstrap/app.php

.....
require __DIR__. '/../routes/user.php';
.....

Kemudian kalian service ditest menggunakan postman

Create Users
Read users index
Read user berdasarkan userid
Update users

Service Customers Address

Buat migration customer address dengan menuliskan perintah diterminal.

Lalu buka file database/migrations/2020_10_23_150316_create_customers_address_table.php, kemudian samakan dengan kode berikut :

.... 
public function up()
    {
        Schema::create('customers_address', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('user_id')->unsigned();
            $table->bigInteger('address_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('no action');
            $table->foreign('address_id')->references('id')->on('address')->onDelete('cascade')->onUpdate('no action');
            $table->timestamps();
        });
    }
....

Kalau sudah lakukan migrate dengan menuliskan diterminal

php artisan migrate

Kemudian buat file model customers address didalam folder app/models.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class Customersaddress extends Model
{
    protected $table = 'customers_address';
    protected $fillable = [
      'address_id',
      'user_id'
    ];

    public function adress()
    {
        return $this->belongsToMany(Address::class);
    }
    
    public function users()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

}

Nb: Function address dan users digunakan untuk menyambungkan masing – masing model ke model customersaddress.

Kalau sudah kalian buat controller CustomersAddress.php didalam folder app/Http/Controller. kemudian samakan kode, sebagai berikut :

<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseHelper;
use App\Http\Controllers\Controller;
use App\Models\Customersaddress;
use App\Models\Address;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CustomeraddressController extends Controller
{
    private $response;

    public function __construct(ResponseHelper $response)
    {
        $this->response = $response;
    }

    public function index(Request $request)
    {
        $userId = $request->user_id;
        $customersaddress = Customersaddress::when($userId, function ($query, $userId) {
                                return $query->where('user_id', $userId);
                            })
                            ->latest();
        if ($request->name) {
            $customersaddress->search("$request->name");
        }
        $customersaddress = $customersaddress->paginate();
        return $this->response->successResponse($customersaddress);
    }
    
    public function show($customersaddress)
    {
        $customersaddress = Customersaddress::findOrFail($customersaddress);
        
        try {
            return $this->response->successResponse($customersaddress);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->response->failedResponse($e);
        }
    }

    public function create(Request $request)
    {
        $this->validateRequest($request);

        $user       = User::where('id', $request->user_id)->first();
        $address    = Address::where('id', $request->address_id)->first();
        
        try {
            ;
            DB::beginTransaction();
            $customersaddress = new Customersaddress;
            $customersaddress->user_id = $user->id;
            $customersaddress->address_id = $address->id;
            $customersaddress->save();
            DB::commit();

            return $this->response->successResponse($customersaddress);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->response->failedResponse($e);
        }
    }
    
    public function update(Request $request, $customersaddress)
    {
        $this->validateRequest($request);
        $data = $request->all();
        try {
            ;
            DB::beginTransaction();
            $customersaddress = Customeraddress::findOrFail($subdistrict);
            $customersaddress->update($data);
            DB::commit();

            return $this->response->successResponse($subdistrict);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->response->failedResponse($e);
        }
    }

    public function destroy($customersaddress)
    {
        $customersaddress = Customersaddress::findOrFail($customersaddress);
        // $customersaddress->delete();
        return $this->response->successResponse($customersaddress);
    }

    function validateRequest($request)
    {
        $this->validate($request, [
            'user_id' => 'required',
            'address_id' => 'required'
        ]);
    }
}

NB: Pada function index terdapat method when, nah method ini fungsinya ketika ada sebuah request makan function didalam method akan dijalankan. Contoh method nantinnya akan dijalankan dicontroller User Detail atau kebutuhan lainnya

Selanjutnya kita buat route customersaddress.php didalam folder routes/

<?php
$router->group(['prefix' => 'customersaddress'], function () use ($router) {
    $router->get('/', ['uses' => '[email protected]']);
    $router->get('/{customersaddress}', ['uses' => '[email protected]']);
    $router->post('/', ['uses' => '[email protected]']);
    $router->post('/{customersaddress}', ['uses' => '[email protected]']);
    $router->delete('/{customersaddress}', ['uses' => '[email protected]']);
});

Kemudian tambahkan kode untuk define route customers address didalam file bootstrap/app.php

....
require __DIR__. '/../routes/customersaddress.php';
....

Jika sudah kita akan testing untuk menambahkan identitas user dengan menggunakan postman

Menambahkan alamat user
Read customer address index
Read customers address berdasarkan id customersaddress

Kesimpulan:

  1. CRUD untuk service users dan customers address
  2. Penggunaan when method sangat dianjurkan
  3. User hanya memiliki 1 alamat

Pembahasan diartikel ini sampai disini, artikel selanjutnya saya akan membahas service community.

Geekgarden adalah salah satu perusahaan yang menyediakan jasa pembuatan platform dan konsultan sistem informasi maupun konsultan aplikasi dengan harga jasa pembuatan sistem informasi yang lebih terjangkau dan standar biaya pembuatan aplikasi sesuai dengan kualitas.

Semoga bermanfaat dan sampai dipembahasan lainnya.

Referensi:

https://laravel.com/docs/8.x/eloquent

https://laravel.com/docs/8.x/queries

Tinggalkan Balasan