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

 
101번째 줄: 101번째 줄:


몇 가지 더 Chirp를 작성하거나, 다른 계정을 등록하고 대화를 시작해 보세요!
몇 가지 더 Chirp를 작성하거나, 다른 계정을 등록하고 대화를 시작해 보세요!
==같이 보기==
* [[Blade로 Chirper 구축 - Chirps 편집]]

2024년 6월 18일 (화) 02:16 기준 최신판

1 개요[ | ]

04. Showing Chirps
04. Chirps 표시

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

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

2 Chirp 조회하기[ | ]

이제 ChirpController 클래스의 index 메서드를 업데이트하여 모든 사용자의 Chirp를 인덱스 페이지로 전달해 보겠습니다:

app/Http/Controllers/ChirpController.php
<?php
...
class ChirpController extends Controller
{
    /**
     * 리소스 목록을 표시합니다.
     */
    public function index(): View
    {
        return view('chirps.index', [
            'chirps' => Chirp::with('user')->latest()->get(),
        ]);
    }
    ...
}

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

Note

한 번에 모든 Chirp를 반환하는 것은 프로덕션 환경에서 규모 확장이 어려울 수 있습니다. 성능을 개선하기 위해 Laravel의 강력한 페이지네이션 기능을 확인해 보세요.

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" 관계의 역관계입니다.

4 뷰 업데이트하기[ | ]

다음으로, chirps.index 컴포넌트를 업데이트하여 폼 아래에 Chirps를 표시해보겠습니다:

resources/views/chirps/index.blade.php
<x-app-layout>
    <div class="max-w-2xl mx-auto p-4 sm:p-6 lg:p-8">
        <form method="POST" action="{{ route('chirps.store') }}">
            @csrf
            <textarea
                name="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"
            >{{ old('message') }}</textarea>
            <x-input-error :messages="$errors->store->get('message')" class="mt-2" />
            <x-primary-button class="mt-4">{{ __('Chirp') }}</x-primary-button>
        </form>
 
        <div class="mt-6 bg-white shadow-sm rounded-lg divide-y">
            @foreach ($chirps as $chirp)
                <div class="p-6 flex space-x-2">
                    <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>
    </div>
</x-app-layout>

이제 브라우저를 열고 이전에 작성한 메시지를 확인해 보세요!

Chirp-index-blade.png

몇 가지 더 Chirp를 작성하거나, 다른 계정을 등록하고 대화를 시작해 보세요!

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