[Laravel] 2장 CURD 기능 구현하기

1. Laravel CURD 구현

Laravel에서 CRUD(Create, Read, Update, Delete) 기능을 구현하는 방법에 대해 단계별로 설명해보겠습니다. 먼저 프로젝트를 설치해야 합니다. 아래 명령어로 Laravel 프로젝트를 생성합니다.

composer create-project --prefer-dist laravel/laravel laravel-crud

 

프로젝트 폴더에 .env 파일을 열고 데이터베이스 연결 정보를 설정합니다.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

 

다임 Post 모델을 위한 마이크레이션 파일을 생성합니다.

php artisan make:migration create_posts_table --create=posts

 

database/migrations/xxxx_xx_xx_create_posts_table.php 파일을 열고, 아래와 같이 수정합니다.

public function up()
{
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string("title");
            $table->text('content');
            $table->timestamps();
});
}

 

아래 명령어로 php 마이그래이션을 실행합니다.

php artisan migrate

 

이제 Post에 대한 모델을 생성해주고 Post관련 CURD 작업을 수행할 컨트롤러를 생성합니다.

php artisan make:model Post

 

Post 관련 CRUD 작업을 수행할 컨트롤러를 생성합니다.

php artisan make:controller PostController --resource

 

routes/web.php를 열고, 아래와 같이 라우트를 설정합니다.

use App\Http\Controllers\PostController;

Route::resource('posts', PostController::class);

 

app/Http/Controllers/PostController.php파일을 열고, CRUD 메서드를 구현합니다.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }

    public function create()
    {
        return view('posts.create');
    }

 
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'content' => 'required',
        ]);

        Post::create($request->all());
        return redirect()->route('posts.index')->with('success', 'Post created successfully');
    }

 
    public function show(Post $post)
    {
        return view('posts.show', compact('post'));
    }

    public function edit(string $id)
    {
        return view('posts.edit', compact('post'));
    }

    public function update(Request $request, Post $post)
    {
        $request->validate([
            'title' => 'required',
            'content' => 'required',
        ]);

        $post->update($request->all());
        return redirect()->route('posts.index')->with('success', 'Post updated successfully');
    }

    public function destroy(Post $post)
    {
        $post->delete();
        return redirect()->route('posts.index')->with('success', 'Post deleted successfully.');
    }
}

 

다음은 view를 생성하기 위해 resources/views/posts 디렉토리를 생성하고 index.blade.php 파일을 생성해 다음 코드를 입력해줍니다.

{{-- resources/views/posts/create.blade.php --}}
@extends('layouts.app')

@section('content')
  <h1>Posts</h1>
  <form action="{{  route('posts.store') }}" method="POST">
    @csrf
    <input type="text" name="title" placeholder="Title" required>
    <textarea name="content" placeholder="Content" required></textarea>
    <button type="submit">Create</button>
  </form>

  @endsection
{{-- resources/views/posts/edit.blade.php --}}
@extends('layouts.app')

@section('content')
   <h1>Posts</h1>
   <a href="{{ route('posts.create') }}">Create New Post</a>
   <ul>
    @foreach ($posts as $post)
     <li>
        <a href="{{ route('posts.show', $post->id) }}">{{ $post->title }}</a>
        <a href="{{ route('posts.edit', $post->id) }}">Edit</a>
        <form action="{{ route('posts.destroy', $post->id) }}" method="POST" style="display:inline">
            @csrf
            @method('DELETE')
            <button type="submit">Delete</button>
        </form>
     </li>
     @endforeach
   </ul>
@endsection
{{-- resources/views/posts/show.blade.php --}}
@extends('layouts.app')

@section('content')
 <h1>{{ $post->title }}</h1>
 <p>{{ $post->content }}</p>
 <a href={{ route('posts.index') }}>Back to Posts</a>
@endsection

 

이제 resources/views/layouts/app.blade.php 파일을 생성해 기본 레이아웃을 정의합니다.

{{-- resources/views/layouts/app.blade.php --}}
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel CRUD</title>
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html>

 

이제 터미널에서 서버를 실행해 CRUD 기능을 테스트 합니다.

php artisan serve
http://localhost:8000/posts

 

이제 CRUD 애플리케이션이 정상적으로 실행되는 것을 확인해봅니다.


 

 

GitHub - Koras02/laravel-bloging

Contribute to Koras02/laravel-bloging development by creating an account on GitHub.

github.com

 

LIST