Flutter
Lumen

Hari Ke-6


Lumen adalah salah satu micro framework PHP yang di miliki oleh framework Laravel. Lumen di buat oleh pengembang laravel untuk membuat projek yang skala nya lebih kecil agar lebih ringan.
Secara umum lumen digunakan untuk membuat web services REST API dengan serialisasi nya menggunakan data JSON.
Composer adalah depedency manager pada PHP, yang menghubungkan projek aplikasi kita dengan library/package dari luar atau dari website https://packagist.org/

Install Composer
composer create-project --prefer-dist laravel/lumen restofoodMembuat Project Lumen Via create-project
Membuat Project Lumen Via Lumen Installer
atau
composer global require "laravel/lumen-installer"
lumen new restofoodphp -S localhost:8000 -t publicMenjalankan Server Lumen
Atau bisa dijalankan di Xampp
http://localhost/restofood/public/http://localhost:8000/
$router->get('/hello', function () {
return "<h1>meetap</h1><p>Selamat Datang di meetap</p>";
});
Routing
Berikut ini 6 routing yang dapat digunakan di Lumen.
- GET - PATCH
- POST - DELETE
- PUT - OPTIONS
Routing adalah suatu jalur awal ketika terdapat akses suatu URL dari halaman browser.
routes/web.php
Middleware
Middleware adalah mekanisme pembatasan akses untuk mengatur permintaan yang masuk ke halaman website atau bisa dikatakan filtering.
<?php
namespace App\Http\Middleware;
use Closure;
class AksesMiddleware
{
public function handle($request, Closure $next)
{
if ($request->akses != "admin") {
return "Akses Ditolak";
}
return $next($request);
}
}app/http/Middleware/AksesMiddleware.php
bootstrap/app.php
$app->routeMiddleware([
'akses' => App\Http\Middleware\AksesMiddleware::class,
]);routes/web.php
$router->get("/adminarea/{akses}", ['middleware' => 'akses', function ($akses) {
return $akses ." Area ";
}]);

Controllers
Configurations

.env
APP_NAME=Lumen
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_TIMEZONE=UTC
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=foods
DB_USERNAME=root
DB_PASSWORD=
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
Buat Database

composer.json
"require": {
"php": "^7.2",
"laravel/lumen-framework": "^6.0",
"cocur/slugify": "^4.0",
"flipbox/lumen-generator": "^6.0",
"irazasyed/larasupport": "^1.6"
},
composer require flipbox/lumen-generator
composer update

uncomment

boostrap/app.php
Migrations

CreateFoods
Schema::create('foods', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('description');
$table->text('full_description');
$table->integer('price');
$table->string('image');
$table->timestamps();
});php artisan make:migration createFoods CreateUsers
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username');
$table->string('password');
$table->string('email');
$table->timestamps();
});php artisan make:migration CreateUsersCreateProfile
Schema::create('profile', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('nama');
$table->string('nik');
$table->string('tanggal_lahir');
$table->string('alamat');
$table->string('path_photo');
$table->string('file_photo');
$table->string('jenis_kelamin');
$table->string('kota');
$table->unsignedInteger('user_id');
});php artisan make:migration CreateProfileCreateCity
Schema::create('city', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});php artisan make:migration CreateCity php artisan migrate
Seeds

UsersTableSeeder
public function run()
{
DB::table('users')->insert([
[
'username' => 'Administrator',
'email' => 'admin@app.com',
'password' => md5('password'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
],
[
'username' => 'Agency',
'email' => 'agency@app.com',
'password' => md5('password'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
],
[
'username' => 'End',
'email' => 'endcustomer@app.com',
'password' => md5('password'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]
]);
}php artisan make:seeder UsersTableSeederFoodsTableSeeder
public function run()
{
$now = date('Y-m-d H:i:s');
DB::table('foods')->delete();
$foodsData = [
[
'title' => 'Bakso',
'description' => 'Bakso Gepeng',
'full_description' => 'Bakso Gepeng Enak',
'price' => 15000,
'image' => '',
'created_at' => $now,
'updated_at' => $now
],
[
'title' => 'Mie',
'description' => 'Mie Goreng',
'full_description' => 'Mie Goreng Enak',
'price' => 20000,
'image' => '',
'created_at' => $now,
'updated_at' => $now
],
];
DB::table('foods')->insert($foodsData);
}php artisan make:seeder FoodsTableSeederCityTableSeeder
public function run()
{
for ($i=0; $i < 100; $i++) {
DB::table('city')->insert([
'name' => 'Kota ' . Str::random(5),
'created_at'=>date('Y-m-d H:i:s'),
'updated_at'=>date('Y-m-d H:i:s'),
]);
}
}php artisan make:seeder CityTableSeederuse Illuminate\Support\Str;DatabaseSeeder
public function run()
{
$this->call([
UsersTableSeeder::class,
FoodsTableSeeder::class,
CityTableSeeder::class,
]);
}php artisan db:seed
php artisan db:seed --class=UsersTableSeederphp artisan migrate:refresh --seedRoutes

Web.php
<?php
$router->group([
'prefix' => 'api'
], function() use ($router) {
//Route for foods
$router->group([
'prefix' => 'foods'
], function() use ($router) {
$router->get('/', 'FoodsController@index');
$router->post('/', 'FoodsController@store');
$router->get('/{id}', 'FoodsController@show');
$router->delete('/{id}', 'FoodsController@destroy');
$router->put('/{id}', 'FoodsController@update');
});
//Route for authentications
$router->group([
'prefix' => 'auth'
], function() use ($router) {
$router->post('/register', 'AuthController@register');
$router->post('/login', 'AuthController@login');
});
//Route for city
$router->group([
'prefix' => 'city'
], function() use ($router) {
$router->post('/', 'CityController@store');
$router->get('/', 'CityController@index');
$router->delete('/{id}', 'CityController@delete');
});
});Resources
FoodResource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class FoodResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'full_description' => $this->full_description,
'price' => $this->price,
'image' => url('/') . $this->image,
];
}
}
UserResource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class UserResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'username' => $this->username,
'email' => $this->email,
'nik' => $this->profile->nik,
'tanggal_lahir' => $this->profile->tanggal_lahir,
'alamat' => $this->profile->alamat,
'jenis_kelamin' => $this->profile->jenis_kelamin,
'kota' => $this->profile->kota,
'path_photo' => url('/') . $this->profile->path_photo,
'file_photo' => $this->profile->file_photo,
];
}
}
Models

Foods.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Foods extends Model
{
protected $table = 'foods';
protected $fillable = [
'title', 'description', 'full_description',
'price', 'image'
];
public function isExists($title) {
$data = $this->where('title', $title)->first();
if ($data) {
return true;
} else {
return false;
}
}
public function isExistsById($id) {
$data = $this->find($id);
if ($data) {
return true;
} else {
return false;
}
}
}
User.php
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'password', 'email',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $table = "profile";
protected $fillable = [
'nama', 'nik', 'tanggal_lahir', 'alamat',
'path_photo', 'file_photo', 'jenis_kelamin',
'kota'
];
public $timestamps = false;
public function user()
{
return $this->belongsTo(User::class);
}
}
City.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
protected $table = "city";
protected $fillable = ['name'];
}
FileManager.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cocur\Slugify\Slugify;
use Illuminate\Support\Str;
class FileManager extends Model
{
private $slug;
public $fileResult;
public function __construct()
{
$this->slug = new Slugify();
}
public function saveData($file, $title ,$path) {
//upload file images
$filePath = public_path() . $path;
$fileName = $this->slug->slugify($title) . '-' . Str::random(10) .'.png';
$file->move($filePath, $fileName);
$this->fileResult = $fileName;
return $path . $fileName;
}
public function removeData($path) {
$filePath = public_path() . $path;
unlink($filePath);
}
}
ResponseHandler.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',
]);
}
}
Controllers

FoodsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Foods;
use App\ResponseHandler;
use App\FileManager;
use App\Http\Resources\FoodResource;
use Illuminate\Support\Facades\Validator;
class FoodsController extends Controller
{
private $foods;
private $respHandler;
private $fileManager;
public function __construct() {
$this->foods = new Foods();
$this->respHandler = new ResponseHandler();
$this->fileManager = new FileManager();
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$foods = $this->foods->get();
if ($foods->count() > 0) {
return $this->respHandler->send(200, "Successfully get foods", FoodResource::collection($foods));
} else {
return $this->respHandler->notFound("Foods");
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validate = Validator::make($request->all(), [
'title' => 'required|string',
'description' => 'required|string',
'full_description' => 'required|string',
'price' => 'required|integer',
'image' => 'required'
]);
if ($validate->fails()) {
return $this->respHandler->validateError($validate->errors());
}
$input = $request->all();
if (!$this->foods->isExists($request->title)) {
//Store new data
$path = $this->fileManager
->saveData($request->file('image'), $request->title, '/images/');
$input['image'] = $path;
$createData = $this->foods->create($input);
if ($createData) {
return $this->respHandler->send(200, "Successfully create foods", new FoodResource($createData));
} else {
return $this->respHandler->internalError();
}
} else {
return $this->respHandler->exists("Foods");
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
if ($this->foods->isExistsById($id)) {
$food = $this->foods->find($id);
return $this->respHandler->send(200, "Successfully get food", new FoodResource($food));
} else {
return $this->respHandler->notFound("Foods");
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$validate = Validator::make($request->all(), [
'title' => 'required|string',
'description' => 'required|string',
'full_description' => 'required|string',
'price' => 'required|integer',
'image' => 'required'
]);
if ($validate->fails()) {
return $this->respHandler->validateError($validate->errors());
}
$input = $request->all();
if ($this->foods->isExistsById($id)) {
$foods = $this->foods->find($id);
$this->fileManager->removeData($foods->image);
//Store new data
$path = $this->fileManager
->saveData($request->file('image'), $request->title, '/images/');
$input['image'] = $path;
$updateData = $foods->update($input);
if ($updateData) {
return $this->respHandler->send(200, "Successfully update foods");
} else {
return $this->respHandler->internalError();
}
} else {
return $this->respHandler->notFound("Foods");
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
if ($this->foods->isExistsById($id)) {
$food = $this->foods->find($id);
$food->delete();
return $this->respHandler->send(200, "Successfully delete food");
} else {
return $this->respHandler->notFound("Foods");
}
}
}
CityController
<?php
namespace App\Http\Controllers;
use App\City;
use App\ResponseHandler;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class CityController extends Controller
{
private $city;
private $respHandler;
public function __construct()
{
$this->respHandler = new ResponseHandler();
$this->city = new City();
}
public function index()
{
$city = $this->city->get();
if ($city->count() > 0) {
return $this->respHandler->send(200, "Successfully get city", $city);
} else {
return $this->respHandler->notFound("City");
}
}
public function store(Request $request)
{
$validate = Validator::make($request->all(), [
'name' => 'required|string'
]);
//if validation failed then return back
if ($validate->fails()) {
return $this->respHandler->validateError($validate->errors());
}
$input = $request->all();
//Check if city not exists
if (!$this->city->where('name', $input['name'])->first()) {
$city = $this->city->create($input);
if ($city) {
return $this->respHandler->send(201, "City successfully created");
} else {
return $this->respHandler->internalError();
}
} else {
return $this->respHandler->exists("City");
}
}
public function delete($id)
{
$city = $this->city->find($id);
if ($city) {
$city->delete();
return $this->respHandler->send(200, "Successfully delete city");
} else {
return $this->respHandler->notFound("City");
}
}
}
AuthController
<?php
namespace App\Http\Controllers;
use App\FileManager;
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;
private $fileManager;
public function __construct()
{
$this->user = new User();
$this->respHandler = new ResponseHandler();
$this->fileManager = new FileManager();
}
public function register(Request $request)
{
$validate = Validator::make($request->all(), [
'username' => 'required|string',
'password' => 'required|string',
'email' => 'required|string|email',
'nama' => 'required|string',
'nik' => 'required',
'tanggal_lahir' => 'required',
'alamat' => 'required|string',
'image' => 'required',
'jenis_kelamin' => 'required',
'kota' => 'required'
]);
//if validation failed then return back
if ($validate->fails()) {
return $this->respHandler->validateError($validate->errors());
}
//set all request to variable input
$input = $request->all();
//Check if users is not already registered
if (!$this->user->where('username', $input['username'])->where('email', $input['email'])->first()) {
//Encrypting password
$input['password'] = Hash::make($input['password']);
//Storing images
$input['path_photo'] = $this->fileManager->saveData($request->file('image'), $input['username'], '/images/users/');
$input['file_photo'] = $this->fileManager->fileResult;
//Inserting data users
$user = $this->user->create($input);
$user->profile()->create($input);
//We are except the password to response
return $this->respHandler->send(201, "Successfully register account", 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 validation failed then return back
if ($validate->fails()) {
return $this->respHandler->validateError($validate->errors());
}
//set all request to variable input
$input = $request->all();
//Check if username exists;
$user = $this->user->where('username', $input["username"])->first();
if ($user) {
//Checking password
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 hari jago flutter hari 6
By flutter id
10 hari jago flutter hari 6
10harijagoflutterhari4
- 740