Laravel RestAPI 구현하기 (1) - 모델링
- 문득, 남이 만들어 놓은 API만 사용 해 봤지 스스로 API를 만들어 본 적이 없다는 것이 생각났다.
- 그래서 laravel을 이용하여 간단한 api 서버를 만들어 보고자 한다.
- 로그인,로그아웃,회원가입, 상품정보조회, 주문하기, 주문 수정삭제, 주문 조회 기능을 API로 구현하고자 한다.
Model 구성 및 마이그레이션 파일 생성하기
- user는 라라벨 migration을 통해 초기에 생성되는 스키마를 활용 할 예정이다.
- 상품에 해당하는 Product, 주문에 해당하는 Order만 구성하도록 한다.
- make:migration을 통하여 2개의 마이그레이션 파일 생성하자.
# 상품 스키마 생성
$ php artisan make:migration CreateProductsTable
# 주문 스키마 생성
$ php artisan make:migration CreateOrdersTable
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id()
->comment('상품id');
$table->string('name',255)
->comment('상품명');
$table->bigInteger('price')
->comment('상품금액');
$table->foreignId('user_id')->constrained('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
- 다 되었으면 artisan migrate 명령을 통하여 스키마 생성해주기.
Factory를 사용하여 상품 더미 데이터 입력하기
- 상품데이터를 많이 수기로 등록하기 힘들기 때문에, Eloquent에서 제공하는 Factories를 사용하여 더미 데이터를 만들어준다.
- 위에서 생성한 스키마를 사용해 주기 위해 모델을 만들면서 , Product 모델에 Factories 적용한다.
- Factory 사용에 대한 자세한 설명은 아래 링크를 참조한다.
- https://www.lesstif.com/php-and-laravel/8-model-factory-test-data-113346851.html
라라벨 8 model factory 로 test data 만들기
www.lesstif.com
- seeder를 사용하여 factory create 작업을 해준다.
- seeder는 마이그레이션 작업시 한번에 등록되게 하기 위해 마이그레이션 up쪽으로 합치기
- 본인의 경우 addDumpDataInProductsTable이란 마이그레이션 파일 하나를 더 생성하여 작업했다.
$ php artisan make:migration AddDumpDataInProductsTable
<?php
namespace Database\Seeders;
use App\Models\Product;
use Illuminate\Database\Seeder;
class FakeDataIntoProductsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// 전체삭제
Product::truncate();
// factory 사용하여 더미 데이터 입력
Product::factory()
->count(100)
->create();
}
}
마무리
- 상품 데이터 대량 등록까지 마치기 위하여 아래 명령어로 마이그레이션을 완수한다.
$ php artisan migrate
'Laravel' 카테고리의 다른 글
Laravel RestAPI 구현하기 (3) - 상품조회,주문,주문조회 구현 (0) | 2022.03.02 |
---|---|
Laravel RestAPI 구현하기 (2) - 회원가입,로그인,로그아웃 구현 (1) | 2022.03.02 |
Local 환경에서 개발 후, 서버 배포시 'Class Not Found' 오류 현상 (0) | 2022.02.08 |
What is Laravel EncryptCookies ???? (0) | 2020.05.26 |
라라벨 pagination Https 적용, how to convert pagination http to https? (1) | 2020.05.20 |