Livewire로 Chirper 구축 - Chirps 생성

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 내비게이션 메뉴[ | ]

Breeze에서 제공하는 내비게이션 메뉴에 링크를 추가해봅시다.

데스크톱 화면에 대한 메뉴 항목을 추가하려면 Breeze에서 제공하는 navigation.blade.php 컴포넌트를 업데이트하세요:

resources/views/livewire/layout/navigation.blade.php
<div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
    <x-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')" wire:navigate>
        {{ __('Dashboard') }}
    </x-nav-link>
    <x-nav-link :href="route('chirps')" :active="request()->routeIs('chirps')" wire:navigate>
        {{ __('Chirps') }}
    </x-nav-link>
</div>

모바일 화면에도 추가하려면:

resources/views/livewire/layout/navigation.blade.php
<div class="pt-2 pb-3 space-y-1">
    <x-responsive-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')" wire:navigate>
        {{ __('Dashboard') }}
    </x-responsive-nav-link>
    <x-responsive-nav-link :href="route('chirps')" :active="request()->routeIs('chirps')" wire:navigate>
        {{ __('Chirps') }}
    </x-responsive-nav-link>
</div>

6 Chrip 저장[ | ]

우리의 폼은 Chirp 버튼을 클릭할 때 store 액션을 호출하도록 설정되어 있습니다. 이제 데이터를 검증하고 새 Chirp를 생성하기 위해 chirp.create 컴포넌트에 store 액션을 추가하겠습니다.

resources/views/livewire/chirps/create.blade.php
<?php
 
use Livewire\Attributes\Validate;
use Livewire\Volt\Component;
 
new class extends Component
{
    #[Validate('required|string|max:255')]
    public string $message = '';
 
    public function store(): void
    {
        $validated = $this->validate();
 
        auth()->user()->chirps()->create($validated);
 
        $this->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>

Livewire의 Validate 속성을 사용하여 사용자가 데이터베이스 컬럼의 255자 제한을 초과하지 않는 메시지를 제공하도록 하기 위해 Laravel의 강력한 검증 기능을 활용하고 있습니다.

그 후, chirps 관계를 활용하여 로그인된 사용자에 속하는 레코드를 생성하고 있습니다. 이 관계는 곧 정의할 예정입니다.

마지막으로, message 폼 필드 값을 비우고 있습니다.

7 관계 생성[ | ]

8 대량 할당 보호[ | ]

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

10 테스트[ | ]

10.1 Artisan Tinker[ | ]

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