10 Hari Jago Flutter

Hari 9

Buat Tabel Cart

CREATE TABLE `cart` (
  `id` int(11) NOT NULL,
  `username` varchar(20) DEFAULT NULL,
  `foods_id` int(11) NOT NULL,
  `qty` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indeks untuk tabel `cart`
--
ALTER TABLE `cart`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT untuk tabel yang dibuang
--

--
-- AUTO_INCREMENT untuk tabel `cart`
--
ALTER TABLE `cart`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

Routes

    $router->group([
        'prefix' => 'cart'
    ], function() use ($router) {
        $router->get('/', 'CartController@index');
        $router->post('/', 'CartController@store');
        $router->get('/{id}', 'CartController@show');
        $router->delete('/{id}', 'CartController@destroy');
        $router->put('/{id}', 'CartController@update');
    });

Model : Cart

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cart extends Model
{
    protected $table = 'cart';
    protected $fillable = [
        'username', 'foods_id', 'qty'
    ];

    public function isExists($username,$foods_id) {
        $data = $this->where('username', $username)->where('foods_id', $foods_id)->first();
        if ($data) {
            return true;
        } else {
            return false;
        }
    }

    public function isExistsById($id) {
        $data = $this->find($id);
        if ($data) {
            return true;
        } else {
            return false;
        }
    }

    public function isExistsByUsername($username) {
        $data = $this->where('username', $username)->first();
        if ($data) {
            return true;
        } else {
            return false;
        }
    }
}

CartResource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class CartResource 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,
            'foods_id' => $this->foods_id,
            'qty' => $this->qty
            
        ];
    }
}

CartController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Cart;
use App\ResponseHandler;
use App\FileManager;
use App\Http\Resources\CartResource;
use Illuminate\Support\Facades\Validator;

class CartController extends Controller
{
    private $cart;
    private $respHandler;
    private $fileManager;
    public function __construct() {
        $this->cart = new cart();
        $this->respHandler = new ResponseHandler();
        $this->fileManager = new FileManager();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cart = $this->cart->get();
        if ($cart->count() > 0) {
            return $this->respHandler->send(200, "Successfully get cart", CartResource::collection($cart));
        } else {
            return $this->respHandler->notFound("cart");
        }

    }

    /**
     * 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(), [
            'username' => 'required|string',
            'foods_id' => 'required|string',
            'qty' => 'required|string'
        ]);

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

        $input = $request->all();
        if (!$this->cart->isExists($request->username,$request->foods_id)) {

            $createData = $this->cart->create($input);
            if ($createData) {
                return $this->respHandler->send(200, "Successfully create cart", new CartResource($createData));
            } else {
                return $this->respHandler->internalError();
            }

        } else {
            return $this->respHandler->exists("cart");
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        if ($this->cart->isExistsById($id)) {
            $cart = $this->cart->find($id);
            return $this->respHandler->send(200, "Successfully get Cart", new CartResource($cart));
        } else {
            return $this->respHandler->notFound("cart");
        }
    }

    /**
     * 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(), [
            'username' => 'required|string',
            'foods_id' => 'required|string',
            'qty' => 'required|string'
        ]);

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

        $input = $request->all();
        if ($this->cart->isExistsById($id)) {
            $cart = $this->cart->find($id);

            $updateData = $cart->update($input);

            if ($updateData) {
                return $this->respHandler->send(200, "Successfully update cart");
            } else {
                return $this->respHandler->internalError();
            }
        } else {
            return $this->respHandler->notFound("cart");
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($username)
    {
        if ($this->cart->isExistsByUsername($username)) {
            $cart = $this->cart->where('username', $username)->get();
            foreach ($cart as $row) {
                $row->delete();
            }
            
            return $this->respHandler->send(200, "Successfully delete cart");
        } else {
            return $this->respHandler->notFound("cart");
        }
    }
}

endpoint

static String baseCart = "${_baseURL}/cart";

cart_model

{
    "status": 200,
    "message": "Successfully get cart",
    "data": [
        {
            "id": 9,
            "username": "uu",
            "foods_id": 2,
            "qty": 1
        }
    ]
}

Json

Model


import 'dart:io';
import 'package:dio/dio.dart';

class CartModel {
  String id;
  String username;
  String foods_id;
  String qty;


  CartModel({
    this.id, this.foods_id, this.qty, this.username
  });

  //Converter dari map ke object
  factory CartModel.fromJson(Map<String, dynamic> json) {
    return CartModel(
      id: json['id'].toString(),
      username: json['username'],
      foods_id: json['foods_id'],
      qty: json['qty']
    );
  }

  //Converter dari object ke map
  Map<String, dynamic> toMap() {
    var map = Map<String, dynamic>();
		if (id != null) {
			map['id'] = id;
		}
		map['username'] = username;
		map['foods_id'] = foods_id;
    map['qty'] = qty;
		
		return map;
  }
}

class CartResponse {
  int status;
  String message;

  CartResponse({this.status, this.message});

  factory CartResponse.fromJson(Map<String, dynamic> json) {
    return CartResponse(
      status: int.parse(json['status'].toString()),
      message: json['message']
    );
  }
}

cart_services


import 'package:restofood_api/core/config/endpoint.dart';
import 'package:dio/dio.dart';
import 'package:restofood_api/core/models/cart_model.dart';

class CartServices {
  static Dio dio = new Dio();

  static Future<List<CartModel>> getAll() async {
    var response = await dio.get(
      Endpoint.baseCart,
      options: Options(
        headers: {
          "Accept": "application/json"
        }
      )
    );

    var _cartData = List<CartModel>();
    response.data["data"].forEach((value) {
      _cartData.add(CartModel.fromJson(value));
    });

    return _cartData;
  }

  static Future<CartResponse> createCart(CartModel cartModel) async {
    var response = await dio.post(
      Endpoint.baseCart,
      data: FormData.fromMap(cartModel.toMap()),
      options: Options(
        headers: {
          "Accept": "application/json"
        }
      )
    );

    return CartResponse.fromJson(response.data);
  }

  static Future<CartResponse> updateCart(CartModel cartModel, String id) async {
    
    var foodData = cartModel.toMap();
    foodData['_method'] = "PUT";

    var response = await dio.post(
      Endpoint.baseCart + "/${id}",
      data: FormData.fromMap(foodData),
      options: Options(
        headers: {
          "Accept": "application/json",
        }
      )
    );
    
    return CartResponse.fromJson(response.data);
  }

  static Future<CartResponse> deleteCart(String username) async {
    var response = await dio.delete(
      Endpoint.baseCart + '/${username}',
      options: Options(
        headers: {
          "Accept": "application/json"
        }
      )
    );

    return CartResponse.fromJson(response.data);
  }
}

10harijagoflutterhari09

By flutter id

10harijagoflutterhari09

10harijagoflutterhari09

  • 750