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

9번째 줄: 9번째 줄:


==Chirp 조회하기==
==Chirp 조회하기==
Chirp 목록을 가져오기 위해, <code>resources/views/chirps.blade.php</code> 뷰를 업데이트하여 Chirps 목록을 표시하도록 하겠습니다. 이를 위해 새로운 Livewire 컴포넌트를 사용하겠습니다:
{{소스헤더|resources/views/chirps.blade.php}}
<syntaxhighlight lang='php' highlight='4-5'>
<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>
</syntaxhighlight>
이제 새로운 <code>chirps.list</code> Livewire 컴포넌트를 생성해보겠습니다:
<syntaxhighlight lang='bash'>
php artisan make:volt chirps/list --class
</syntaxhighlight>
이 명령어는 <code>resources/views/livewire/chirps/list.blade.php</code>에 새로운 Livewire 컴포넌트를 생성할 것입니다. Livewire 컴포넌트를 업데이트하여 Chirps 목록을 표시해보겠습니다:
{{소스헤더|resources/views/livewire/chirps/list.blade.php}}
<syntaxhighlight lang='php' highlight='3-4,9-16,19-35'>
<?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>
</syntaxhighlight>
여기서 Eloquent의 <code>with</code> 메소드를 사용하여 각 Chirp와 연관된 사용자를 [[Eloquent 관계#사전 로딩|eager-load]]했습니다. 또한 <code>latest</code> 스코프를 사용하여 레코드를 역순으로 반환했습니다.
==사용자를 Chirp에 연결하기==
==사용자를 Chirp에 연결하기==
Laravel이 <code>user</code> 관계를 반환하도록 지시하여 Chirp의 작성자 이름을 표시할 수 있게 했습니다. 하지만 Chirp의 <code>user</code> 관계는 아직 정의되지 않았습니다. 이를 해결하기 위해 <code>Chirp</code> 모델에 새 [https://laravel.com/docs/eloquent-relationships#one-to-many-inverse "belongs to"] 관계를 추가해보겠습니다:
Laravel이 <code>user</code> 관계를 반환하도록 지시하여 Chirp의 작성자 이름을 표시할 수 있게 했습니다. 하지만 Chirp의 <code>user</code> 관계는 아직 정의되지 않았습니다. 이를 해결하기 위해 <code>Chirp</code> 모델에 새 [https://laravel.com/docs/eloquent-relationships#one-to-many-inverse "belongs to"] 관계를 추가해보겠습니다:

2024년 7월 8일 (월) 22:00 판

1 개요

Crystal Clear action info.png 작성 중인 문서입니다.
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 스코프를 사용하여 레코드를 역순으로 반환했습니다.

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 }}