Membuat RESTFUL API dengan Laravel 6

Membuat RESTFUL API dengan Laravel 6

Assalamualaikum,

diwaktu senggang menunggu azan ashar, mari kita latihan membuat rest api dengan laravel 6 . Bismillah

  1. Membuat Project Laravel pada xampp/htdocs dengan nama : lararest
composer create-project --prefer-dist laravel/laravel lararest
Install Laravel

2. edit file .env baris 12 – 14

Konfigurasi Database

3. Buat Database Mysql dengan nama : lararest

Database Mysql

4. edit file database/migrations/2014_10_12_000000_create_users_table.php

        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('username');
            $table->string('password');
            $table->string('email');
            $table->timestamps();
        });

5. migrasi tabel dengan perintah

php artisan migrate:refresh

6. ubah app/user.php

model user

7. Buat file app/ResponseHandler.php.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ResponseHandler extends Model
{
    public function send($status = 200, $message, $data = []) {
        return response()->json([
            'status' => $status,
            'message' => $message,
            'data' => $data
        ]);
    }

    public function notFound($message) {
        return response()->json([
            'status' => 404,
            'message' => "$message not found",
        ]);
    }

    public function internalError() {
        return response()->json([
            'status' => 500,
            'message' => "Internal server error",
        ]);
    }

    public function exists($message) {
        return response()->json([
            'status' => 400,
            'message' => "$message already exists",
        ]);
    }

    public function validateError($errors) {
        
        return response()->json([
            'status' => 422,
            'message' => 'Validation errors',
            'error' => $errors
        ]);
    }

    public function badCredentials() {
        
        return response()->json([
            'status' => 401,
            'message' => 'Username or password is wrong',
        ]);
    }
}

8. Buat file app/http/Resources/UserResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class UserResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'email' => $this->email,
        ];
    }
}

9. Buat file app/http/AuthController.php

<?php

namespace App\Http\Controllers;

use App\Http\Resources\UserResource;
use App\ResponseHandler;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Arr;

class AuthController extends Controller
{
    private $user;
    private $respHandler;

    public function __construct()
    {
        $this->user = new User();
        $this->respHandler = new ResponseHandler();
    }

    public function register(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'username' => 'required|string',
            'password' => 'required|string',
            'email' => 'required|string|email'
        ]);

        if ($validate->fails()) {return $this->respHandler->validateError($validate->errors());}

        $input = $request->all();
        
        if (!$this->user->where('username', $input['username'])->where('email', $input['email'])->first()) {

            $input['password'] = Hash::make($input['password']);
            $user = $this->user->create($input);
            return $this->respHandler->send(201, "Register Success", new UserResource($user));
        } else {
            return $this->respHandler->exists("Users");
        }
    }

    public function login(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'username' => 'required|string',
            'password' => 'required'
        ]);

        if ($validate->fails()) {return $this->respHandler->validateError($validate->errors());}

        $input = $request->all();

        $user = $this->user->where('username', $input["username"])->first();
        if ($user) {
            if (Hash::check($input['password'], $user->password)) {
                return $this->respHandler->send(200, "Berhasil login", new UserResource($user));
            } else {
                return $this->respHandler->badCredentials();
            }
        } else {
            return $this->respHandler->notFound("Users");
        }
    }
}

10. Update file routes/api.php

Route::post('/register', 'AuthController@register');
Route::post('/login', 'AuthController@login');

11. Test RESTFUL API REGISTER

http://localhost/lararest/public/api/register

12. test RESTFUL API LOGIN

http://localhost/lararest/public/api/login

Semoga Bermanfaat

Flutter Developer