coyangi
코딩하는 고양이
coyangi
전체 방문자
오늘
어제
  • 분류 전체보기 (23)
    • 🚀 Daily Life (1)
      • 덕질 (1)
      • 회고 (0)
    • 🍎 MAC OS (1)
    • 🔫 Algorithm (1)
      • Goormlevel (0)
    • 🌈 Programming (18)
      • Dart (7)
      • ETC (1)
      • Flutter (4)
      • Git (0)
      • Javascript (1)
      • Laravel (3)
      • PHP (2)
    • 🌎 Server (1)
    • 🧠 Database (0)
      • MySQL (0)
    • 💻 Computer Science (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 플루터
  • json
  • Laravel
  • Class
  • 앱
  • Instance
  • flutter
  • Server
  • parameter
  • 인자
  • 라라벨
  • Containe
  • argument
  • Sizedbox
  • 서버구축
  • 덕질
  • 알고리즘
  • ajax
  • php
  • HOBBY FAIR
  • 데이터 구조
  • 웹서버
  • constructor
  • crud
  • override
  • CENTER
  • config
  • dart
  • XAMPP
  • 맥

최근 글

티스토리

개인정보

  • 티스토리 홈
  • 스토리
  • 포럼
  • 로그인
hELLO · Designed By 정상우.
coyangi

코딩하는 고양이

[Laravel] Ajax로 CRUD 게시판 만들기 (1)
🌈 Programming/Laravel

[Laravel] Ajax로 CRUD 게시판 만들기 (1)

2022. 5. 26. 15:09

📖 MVC(Model View Controller) 기본 셋팅

1. Laravel 프로젝트 생성

우선 cmd 창 혹은 git bash 에서 경로를 지정한 후
컴포저를 사용하여 8.x 버전의 라라벨 프로젝트를 생성합니다.

composer create-project laravel/laravel="8.x" ajax_crud

2. DB 연동 및 table, column 생성

터미널에서 artisan 명령어를 입력하여 모델, 마이그레이션, 컨트롤러 파일을 생성합니다.

php artisan make:model Student -mc

Student.php 모델 파일을 열어 table 및 column 연동합니다.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;
    protected $table = 'students';

    protected $fillable = [
        'name',
        'emil',
        'phone',
        'course',
    ];
}

마이그레이션 파일로 이동해 DB 에 생성할 컬럼들을 작성한 후
터미널에서 php artisan migrate 명령어를 입력합니다.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name')->comment('이름');
            $table->string('email')->comment('이메일');
            $table->string('phone')->comment('핸드폰 번호');
            $table->string('course')->comment('과목');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}

3. Routes 경로 설정

web.php 파일로 이동해 라우터 경로를 추가합니다.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;
Route::get('students', [StudentController::class, 'index']);

Route::get('/', function () {
    return view('welcome');
});

StudentController.php 컨트롤러로 이동해 index 함수를 생성합니다.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class StudentController extends Controller
{
    public function index()
    {
        return view('student.index');
    }
}

4. View 파일 생성

리소스로 이동해 student/index.blade.php, student/layouts/app.blade.php 파일을 생성하고 아래와 같이 입력합니다.

// app.blade.php
<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>AJAX CRUD</title>
    <!-- Style -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div id="app">
        <main class="py-4">
            @yield('content')
        </main>
    </div>

<!-- JQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
// index.blade.php
@extends('student.layouts.app')

@section('content')
@extends('student.layouts.app')

@section('content')
    <!-- AddStudentModel Modal [START] -->
    <div class="modal fade" id="AddStudentModel" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">학생 추가</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="form-group mb-3">
                        <label for="">이름</label>
                        <input type="text" class="name form-control">
                    </div>
                    <div class="form-group mb-3">
                        <label for="">이메일</label>
                        <input type="text" class="email form-control">
                    </div>
                    <div class="form-group mb-3">
                        <label for="">핸드폰 번호</label>
                        <input type="text" class="phone form-control">
                    </div>
                    <div class="form-group mb-3">
                        <label for="">전공</label>
                        <input type="text" class="course form-control">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary add_student">저장</button>
                </div>
            </div>
        </div>
    </div>
    <!-- AddStudentModel Modal [END] -->

    <div class="container py-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h4>학생 정보 리스트
                            <a href="#" data-bs-toggle="modal" data-bs-target="#AddStudentModel" class="btn btn-primary float-end btn-sm">학생 추가</a>
                        </h4>
                    </div>
                    <div class="card-body">

                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

5. 화면 확인

터미널에서 php artisan serve 명령어를 입력해 서버를 구동합니다.
URL 주소창에 http://127.0.0.1:8000/student를 입력하고 아래와 같은 화면이 출력되는지 확인 합니다.




'🌈 Programming > Laravel' 카테고리의 다른 글

[Laravel] .env 파일 설정으로 개발용, 서비스용 URL 나누기  (0) 2023.06.30
[Laravel] JSON with Ajax 리스트 만들기 (1)  (0) 2022.05.23
    '🌈 Programming/Laravel' 카테고리의 다른 글
    • [Laravel] .env 파일 설정으로 개발용, 서비스용 URL 나누기
    • [Laravel] JSON with Ajax 리스트 만들기 (1)
    coyangi
    coyangi
    경기도 모 창고에서 은둔하다 양지 바른 땅으로 올라온 고양이

    티스토리툴바