"Livewire로 Chirper 구축 - Chirps 생성"의 두 판 사이의 차이

 
(같은 사용자의 중간 판 3개는 보이지 않습니다)
9번째 줄: 9번째 줄:


== 모델, 마이그레이션, 컨트롤러 ==
== 모델, 마이그레이션, 컨트롤러 ==
사용자들이 Chirp를 게시할 수 있도록 하려면 모델, 마이그레이션, 컨트롤러를 만들어야 합니다. 각 개념을 좀 더 깊이 살펴보겠습니다:
* [[Laravel Eloquent|모델]]은 데이터베이스의 테이블과 상호작용할 수 있는 강력하고 즐거운 인터페이스를 제공합니다.
* [[Laravel 마이그레이션|마이그레이션]]은 데이터베이스의 테이블을 쉽게 생성하고 수정할 수 있게 해줍니다. 이를 통해 애플리케이션이 실행되는 모든 곳에서 동일한 데이터베이스 구조가 유지되도록 보장합니다.
* [[Laravel 컨트롤러|컨트롤러]]는 애플리케이션에 대한 요청을 처리하고 응답을 반환하는 역할을 합니다.
거의 모든 기능은 이 세 가지 요소가 조화롭게 작동하는 것을 포함하며, <code>artisan make:model</code> 명령어를 사용하면 이 모든 것을 한 번에 생성할 수 있습니다.
Chirp를 위한 모델, 마이그레이션, 컨트롤러를 생성하려면 다음 명령어를 사용하세요:
<syntaxhighlight lang='bash'>
php artisan make:model -mc Chirp
</syntaxhighlight>
{{NOTE}}
<code>php artisan make:model --help</code> 명령어를 실행하여 사용가능한 모든 옵션을 볼 수 있습니다.
{{/NOTE}}
이 명령어는 다음 세 가지 파일을 생성합니다:
* <code>app/Models/Chirp.php</code> - Eloquent 모델
* <code>database/migrations/<timestamp>_create_chirps_table.php</code> - 데이터베이스 테이블을 생성할 데이터베이스 마이그레이션
* <code>app/Http/Controllers/ChirpController.php</code> - 들어오는 요청을 처리하고 응답을 반환할 HTTP 컨트롤러
== 라우팅 ==
== 라우팅 ==
컨트롤러에 대한 URL을 생성하기 위해 <code>routes</code> 디렉토리에 라우트를 추가해야 합니다.
Livewire를 사용하고 있기 때문에, Chirp 생성 폼과 기존 Chirp 목록을 표시하기 위해 단일 <codeRoute::get</code> 라우트만 정의하면 됩니다. 또한, 이 라우트를 두 가지 [[Laravel 미들웨어|미들웨어]] 뒤에 배치할 것입니다:
* <code>auth</code> 미들웨어는 로그인한 사용자만 라우트에 접근할 수 있도록 합니다.
* <code>verified</code> 미들웨어는 [[Laravel 이메일 인증|이메일 인증]]을 활성화할 경우 사용됩니다.
{{소스헤더|routes/web.php}}
<syntaxhighlight lang='php' highlight='3,7-10'>
<?php
use App\Http\Controllers\ChirpController;
use Illuminate\Support\Facades\Route;
Route::view('/', 'welcome');
Route::get('chirps', [ChirpController::class, 'index'])
    ->middleware(['auth', 'verified'])
    ->name('chirps');
Route::view('dashboard', 'dashboard')
    ->middleware(['auth', 'verified'])
    ->name('dashboard');
Route::view('profile', 'profile')
    ->middleware(['auth'])
    ->name('profile');
require __DIR__.'/auth.php';
</syntaxhighlight>
{{NOTE}}
애플리케이션의 모든 라우트를 보려면 <code>php artisan route:list</code> 명령어를 실행하면 됩니다.
{{/NOTE}}
새 <code>ChirpController</code> 클래스의 <code>index</code> 메소드에서 테스트 메시지를 반환하여 라우트와 컨트롤러를 테스트해봅시다:
{{소스헤더|app/Http/Controllers/ChirpController.php}}
<syntaxhighlight lang='php' highlight='5,9-15'>
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
class ChirpController extends Controller
{
    /**
    * Display a listing of the resource.
    */
    public function index(): Response
    {
        return response('Hello, World!');
    }
}
</syntaxhighlight>
이전에 로그인된 상태라면 http://localhost:8000/chirps , 또는 Sail을 사용 중이라면 http://localhost/chirps 로 이동하여 메시지를 확인할 수 있습니다.
== Livewire ==
== Livewire ==
아직까진 별 게 없죠? 이제 <code>ChirpController</code> 클래스의 <code>index</code> 메소드를 업데이트하여 Blade 뷰를 렌더링해 봅시다.
{{소스헤더|app/Http/Controllers/ChirpController.php}}
<syntaxhighlight lang='php' highlight='5,12-17'>
<?php
namespace App\Http\Controllers;
use Illuminate\View\View;
class ChirpController extends Controller
{
    /**
    * Display a listing of the resource.
    */
    public function index(): View
    {
        return view('chirps', [
            //
        ]);
    }
}
</syntaxhighlight>
이제 Blade 템플릿을 생성하고 새로운 Chirp를 생성할 폼을 렌더링하는 Livewire 컴포넌트를 포함해 봅시다:
{{소스헤더|resources/views/chirps.blade.php}}
<syntaxhighlight lang='php'>
<x-app-layout>
    <div class="max-w-2xl mx-auto p-4 sm:p-6 lg:p-8">
        <livewire:chirps.create />
    </div>
</x-app-layout>
</syntaxhighlight>
다음으로, 폼을 렌더링할 Livewire 컴포넌트를 생성합시다. 이를 위해, Artisan 명령어인 <code>make:volt</code>를 사용할 수 있습니다.
아래의 스니펫은 컴포넌트를 생성하는 두 가지 방법을 제시합니다: 하나는 <code>Class</code>(클래스) API를 사용하는 방법이고, 다른 하나는 <code>Functional</code>(함수형) API를 사용하는 방법입니다. 이 튜토리얼 전반에서 두 API를 모두 보실 수 있으며, 선호하는 스타일의 Livewire 개발 방식을 선택하실 수 있습니다.
{{소스헤더|클래스}}
<syntaxhighlight lang='bash'>
php artisan make:volt chirps/create --class
</syntaxhighlight>
이 명령어는 새로운 Livewire 컴포넌트를 <code>resources/views/livewire/chirps/create.blade.php</code>에 생성합니다.
Livewire 컴포넌트를 업데이트하여 폼을 표시해 봅시다:
{{소스헤더|resources/views/livewire/chirps/create.blade.php}}
<syntaxhighlight lang='php' highlight='7,11-20'>
<?php
use Livewire\Volt\Component;
new class extends Component
{
    public string $message = '';
}; ?>
<div>
    <form wire:submit="store">
        <textarea
            wire:model="message"
            placeholder="{{ __('What\'s on your mind?') }}"
            class="block w-full border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm"
        ></textarea>
        <x-input-error :messages="$errors->get('message')" class="mt-2" />
        <x-primary-button class="mt-4">{{ __('Chirp') }}</x-primary-button>
    </form>
</div>
</syntaxhighlight>
이제 브라우저에서 페이지를 새로고침하여 기본 레이아웃에 렌더링된 새로운 폼을 확인하세요!
[[파일:chirp-form.png]]
스크린샷이 위와 같지 않다면, Vite 개발 서버를 중지하고 다시 시작하여 Tailwind가 우리가 방금 만든 새 파일의 CSS 클래스를 감지할 수 있도록 해야 할 수 있습니다.
이 시점부터는 Vite 개발 서버가 <code>npm run dev</code>로 실행 중일 때 Blade 템플릿에 변경사항을 자동으로 브라우저에서 새로고침합니다.
== 내비게이션 메뉴 ==
== 내비게이션 메뉴 ==
== Chrip 저장 ==
== Chrip 저장 ==

2024년 6월 29일 (토) 13:08 기준 최신판

1 개요[ | ]

03. Creating Chirps
03. Chirps 생성

https://bootcamp.laravel.com/livewire/creating-chirps

Crystal Clear action info.png 작성 중인 문서입니다.

이제 새로운 애플리케이션을 만들 준비가 되었습니다! 사용자들이 Chirps라는 짧은 메시지를 게시할 수 있도록 해봅시다.

2 모델, 마이그레이션, 컨트롤러[ | ]

사용자들이 Chirp를 게시할 수 있도록 하려면 모델, 마이그레이션, 컨트롤러를 만들어야 합니다. 각 개념을 좀 더 깊이 살펴보겠습니다:

  • 모델은 데이터베이스의 테이블과 상호작용할 수 있는 강력하고 즐거운 인터페이스를 제공합니다.
  • 마이그레이션은 데이터베이스의 테이블을 쉽게 생성하고 수정할 수 있게 해줍니다. 이를 통해 애플리케이션이 실행되는 모든 곳에서 동일한 데이터베이스 구조가 유지되도록 보장합니다.
  • 컨트롤러는 애플리케이션에 대한 요청을 처리하고 응답을 반환하는 역할을 합니다.

거의 모든 기능은 이 세 가지 요소가 조화롭게 작동하는 것을 포함하며, artisan make:model 명령어를 사용하면 이 모든 것을 한 번에 생성할 수 있습니다.

Chirp를 위한 모델, 마이그레이션, 컨트롤러를 생성하려면 다음 명령어를 사용하세요:

php artisan make:model -mc Chirp

Note

php artisan make:model --help 명령어를 실행하여 사용가능한 모든 옵션을 볼 수 있습니다.

이 명령어는 다음 세 가지 파일을 생성합니다:

  • app/Models/Chirp.php - Eloquent 모델
  • database/migrations/<timestamp>_create_chirps_table.php - 데이터베이스 테이블을 생성할 데이터베이스 마이그레이션
  • app/Http/Controllers/ChirpController.php - 들어오는 요청을 처리하고 응답을 반환할 HTTP 컨트롤러

3 라우팅[ | ]

컨트롤러에 대한 URL을 생성하기 위해 routes 디렉토리에 라우트를 추가해야 합니다.

Livewire를 사용하고 있기 때문에, Chirp 생성 폼과 기존 Chirp 목록을 표시하기 위해 단일 <codeRoute::get 라우트만 정의하면 됩니다. 또한, 이 라우트를 두 가지 미들웨어 뒤에 배치할 것입니다:

  • auth 미들웨어는 로그인한 사용자만 라우트에 접근할 수 있도록 합니다.
  • verified 미들웨어는 이메일 인증을 활성화할 경우 사용됩니다.
routes/web.php
<?php

use App\Http\Controllers\ChirpController;
use Illuminate\Support\Facades\Route;

Route::view('/', 'welcome');

Route::get('chirps', [ChirpController::class, 'index'])
    ->middleware(['auth', 'verified'])
    ->name('chirps');

Route::view('dashboard', 'dashboard')
    ->middleware(['auth', 'verified'])
    ->name('dashboard');

Route::view('profile', 'profile')
    ->middleware(['auth'])
    ->name('profile');

require __DIR__.'/auth.php';

Note

애플리케이션의 모든 라우트를 보려면 php artisan route:list 명령어를 실행하면 됩니다.

ChirpController 클래스의 index 메소드에서 테스트 메시지를 반환하여 라우트와 컨트롤러를 테스트해봅시다:

app/Http/Controllers/ChirpController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;

class ChirpController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): Response
    {
        return response('Hello, World!');
    }
}

이전에 로그인된 상태라면 http://localhost:8000/chirps , 또는 Sail을 사용 중이라면 http://localhost/chirps 로 이동하여 메시지를 확인할 수 있습니다.

4 Livewire[ | ]

아직까진 별 게 없죠? 이제 ChirpController 클래스의 index 메소드를 업데이트하여 Blade 뷰를 렌더링해 봅시다.

app/Http/Controllers/ChirpController.php
<?php

namespace App\Http\Controllers;

use Illuminate\View\View;

class ChirpController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        return view('chirps', [
            //
        ]);
    }
}

이제 Blade 템플릿을 생성하고 새로운 Chirp를 생성할 폼을 렌더링하는 Livewire 컴포넌트를 포함해 봅시다:

resources/views/chirps.blade.php
<x-app-layout>
    <div class="max-w-2xl mx-auto p-4 sm:p-6 lg:p-8">
        <livewire:chirps.create />
    </div>
</x-app-layout>

다음으로, 폼을 렌더링할 Livewire 컴포넌트를 생성합시다. 이를 위해, Artisan 명령어인 make:volt를 사용할 수 있습니다.

아래의 스니펫은 컴포넌트를 생성하는 두 가지 방법을 제시합니다: 하나는 Class(클래스) API를 사용하는 방법이고, 다른 하나는 Functional(함수형) API를 사용하는 방법입니다. 이 튜토리얼 전반에서 두 API를 모두 보실 수 있으며, 선호하는 스타일의 Livewire 개발 방식을 선택하실 수 있습니다.

클래스
php artisan make:volt chirps/create --class

이 명령어는 새로운 Livewire 컴포넌트를 resources/views/livewire/chirps/create.blade.php에 생성합니다.

Livewire 컴포넌트를 업데이트하여 폼을 표시해 봅시다:

resources/views/livewire/chirps/create.blade.php
<?php
 
use Livewire\Volt\Component;
 
new class extends Component
{
    public string $message = ''; 
}; ?>
 
<div>
    <form wire:submit="store"> 
        <textarea
            wire:model="message"
            placeholder="{{ __('What\'s on your mind?') }}"
            class="block w-full border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm"
        ></textarea>
 
        <x-input-error :messages="$errors->get('message')" class="mt-2" />
        <x-primary-button class="mt-4">{{ __('Chirp') }}</x-primary-button>
    </form> 
</div>

이제 브라우저에서 페이지를 새로고침하여 기본 레이아웃에 렌더링된 새로운 폼을 확인하세요!

Chirp-form.png

스크린샷이 위와 같지 않다면, Vite 개발 서버를 중지하고 다시 시작하여 Tailwind가 우리가 방금 만든 새 파일의 CSS 클래스를 감지할 수 있도록 해야 할 수 있습니다.

이 시점부터는 Vite 개발 서버가 npm run dev로 실행 중일 때 Blade 템플릿에 변경사항을 자동으로 브라우저에서 새로고침합니다.

5 내비게이션 메뉴[ | ]

6 Chrip 저장[ | ]

7 관계 생성[ | ]

8 대량 할당 보호[ | ]

9 마이그레이션 업데이트[ | ]

10 테스트[ | ]

10.1 Artisan Tinker[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}