컨트롤러에서 'blog'배열을 받고 모델에서 User와 Blog 관계를 설정 후, 뷰에서 받은 blog배열을 하나씩 출력해준다.
class BlogController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(): View
{
//blog 받기
return view('blog.index',['blog' => Blog::with('user')->latest()->get()]);
}
class Blog extends Model
{
use HasFactory;
protected $fillable = [
'message',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
<div class="mt-6 bg-white shadow-sm rounded-lg divide-y">
//컨트롤러에서 받은 $blog
@foreach ($blog 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>
결과는 아래와 같다. 가장 최신의 글이 가장 위에 보여진다.