"Livewire로 Chirper 구축 - Chirps 표시"의 두 판 사이의 차이

 
1번째 줄: 1번째 줄:
==개요==
==개요==
{{작성중}}
[[분류: Laravel Bootcamp]]
[[분류: Laravel Bootcamp]]
;04. Showing Chirps
;04. Showing Chirps

2024년 7월 8일 (월) 22:05 기준 최신판

1 개요[ | ]

04. Showing Chirps
04. Chirps 표시

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


이전 단계에서 Chirp를 생성하는 기능을 추가했다면, 이제 Chirp를 표시할 준비가 되었습니다!

2 Chirp 조회하기[ | ]

Chirp 목록을 가져오기 위해, resources/views/chirps.blade.php 뷰를 업데이트하여 Chirps 목록을 표시하도록 하겠습니다. 이를 위해 새로운 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 />
        
        <livewire:chirps.list />
    </div>
</x-app-layout>

이제 새로운 chirps.list Livewire 컴포넌트를 생성해보겠습니다:

php artisan make:volt chirps/list --class

이 명령어는 resources/views/livewire/chirps/list.blade.php에 새로운 Livewire 컴포넌트를 생성할 것입니다. Livewire 컴포넌트를 업데이트하여 Chirps 목록을 표시해보겠습니다:

resources/views/livewire/chirps/list.blade.php
<?php
 
use App\Models\Chirp; 
use Illuminate\Database\Eloquent\Collection; 
use Livewire\Volt\Component;
 
new class extends Component
{
    public Collection $chirps; 
 
    public function mount(): void
    {
        $this->chirps = Chirp::with('user')
            ->latest()
            ->get();
    } 
}; ?>
 
<div> 
    // 
<div class="mt-6 bg-white shadow-sm rounded-lg divide-y"> 
    @foreach ($chirps as $chirp)
        <div class="p-6 flex space-x-2" wire:key="{{ $chirp->id }}">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-600 -scale-x-100" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
            <div class="flex-1">
                <div class="flex justify-between items-center">
                    <div>
                        <span class="text-gray-800">{{ $chirp->user->name }}</span>
                        <small class="ml-2 text-sm text-gray-600">{{ $chirp->created_at->format('j M Y, g:i a') }}</small>
                    </div>
                </div>
                <p class="mt-4 text-lg text-gray-900">{{ $chirp->message }}</p>
            </div>
        </div>
    @endforeach 
</div>

여기서 Eloquent의 with 메소드를 사용하여 각 Chirp와 연관된 사용자를 eager-load했습니다. 또한 latest 스코프를 사용하여 레코드를 역순으로 반환했습니다.

Note

프로덕션 환경에서 모든 Chirp을 한 번에 반환하는 것은 확장성이 없습니다. 성능을 개선하기 위해 Laravel의 강력한 페이지네이션 기능을 살펴보겠습니다.

마지막으로, 새로운 Chirp가 생성될 때마다 Chirp 목록을 업데이트해야 합니다. 이를 위해 Livewire 이벤트를 사용할 수 있습니다. 새로운 Chirp가 생성될 때마다 이벤트를 디스패치합시다:

resources/views/livewire/chirps/create.blade.php
<?php
 ...
    public function store(): void
    {
        $validated = $this->validate();
 
        auth()->user()->chirps()->create($validated);
 
        $this->message = '';
 
        $this->dispatch('chirp-created'); 
    }
}; ?> 
 
<div> ...
</div>


이제 chirps.list 컴포넌트를 업데이트하여 chirp-created 이벤트를 수신하고 Chirp 목록을 업데이트할 수 있습니다:

resources/views/livewire/chirps/list.blade.php
<?php
 
use App\Models\Chirp;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\On; 
use Livewire\Volt\Component;
 
new class extends Component
{
    public Collection $chirps;
 
    public function mount(): void
    {
        $this->getChirps(); 
    }
 
    #[On('chirp-created')]
    public function getChirps(): void
    {
        $this->chirps = Chirp::with('user')
            ->latest()
            ->get();
    } 
}; ?>
 
<div class="mt-6 bg-white shadow-sm rounded-lg divide-y">
    ...
</div>

이렇게 하면 새로운 Chirp가 생성될 때마다 목록이 자동으로 업데이트됩니다.

3 사용자를 Chirp에 연결하기[ | ]

Laravel이 user 관계를 반환하도록 지시하여 Chirp의 작성자 이름을 표시할 수 있게 했습니다. 하지만 Chirp의 user 관계는 아직 정의되지 않았습니다. 이를 해결하기 위해 Chirp 모델에 새 "belongs to" 관계를 추가해보겠습니다:

app/Models/Chirp.php
<?php
...
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Chirp extends Model
{
    ...
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

이 관계는 이전에 User 모델에 생성한 "has many" 관계의 역관계입니다.

이제 브라우저에서 이전에 Chirp한 메시지를 확인해보세요!

Chirp-index.png

더 많은 Chirp을 하거나 다른 계정을 등록하고 대화를 시작해보세요!

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