테스트는 안 해 봤습니다. 참고해주세요.
// 1. 일반적인 구현 // Controller $articles = Articles::with('attachments')->latest()->paginate(50); return view('articles.index', [ 'articles' => $articles ]); // View @foreach ($articles as $article) @if ($article->attachments->count() > 0) @foreach ($article->attachments as $attachment) <img src="/path/to/{{ $attachment->filename }}"> @endforeach @endif @endforeach // 2. 좀 더 나은 구현 // Controller $articles = Articles::with('attachments')->latest()->paginate(50); return view('articles.index', [ 'articles' => $articles, 'images' => $this->getImages($articles), ]); private function getImages(\Illuminate\Database\Eloquent\Collection $articles) { return $articles->map(function (\App\Article $article) { if ($article->attachments->count() > 0) { foreach($article->attachments as $attachment) { return $attachment->filename ?? null; } } })->filter(); } // View @foreach ($images as $image) <img src="/path/to/{{ $attachment->filename }}"> @endforeach
글을 작성할때 이미지를 저장했는데, 페이스북 처럼 무한스크롤에서 글과 이미지를 함께 보여주고 싶습니다.
제가 쿼리를 잘 이해를 못해서그런건지 방법이 떠오르질 않습니다.
일단은 이렇게 articles를 다 구해서 무한스크롤뷰에 뿌려는 줫는데 그 articles마다의 이미지 file 이름을 구해올 방법을 모르겟습니다.
blade 뷰에서 아래처럼
이렇게하면 Trying to get property of non-object 이런 에러가뜨고......
어떻게 좋은 방법이 있을까요??