18. Post store

yeomc·2021년 7월 16일
1

라라벨8 레딧

목록 보기
18/22

유효성 검사 store form request 생성

php artisan make:request StorePostRequest
// StorePostRequest.php
public function authorize()
{
  return true;
}

public function rules()
{
  return [
    'title' => 'required',
    'post_text' => 'nullable|string',
    'post_image' => 'nullable|image',
    'post_link' => 'nullable|url'
  ];
}

CommunityPost 컨트롤러 수정

public function store(StorePostRequest $request, Community $community)
{
  $post = $community->posts()->create(Arr::except($request->validated(), 'post_image') + [
    'user_id' => auth()->id()
  ]);

  return redirect()->route('communities.show', $community);
}

Community 컨트롤러 수정

eager 로딩

// show(Community $community)
$posts = $community->posts()->with('user')->latest()->paginate(10);

Community show view 수정

// communities/show.blade.php
// post 표시영역 수정
<div class="mb-2 is-size-7 has-text-grey">
  Posted {{ $post->user->username }}
  {{ ReadableDiffDateTime($post->created_at) }}
</div>
<h5 class="title is-5 mb-3">{{ $post->title }}</h5>
@if ($post->post_link)
  <a href="{{ $post->post_link }}" target="_blank" class="has-text-info">
  <span>{{ Str::words($post->post_link, 100, ' ...') }}</span>
  <span class="icon is-small is-size-7"><i class="fas fa-external-link-alt"></i></span>
  </a>
@endif
@if ($post->post_text)
  <p>{{ Str::words($post->post_text, 100, ' ...') }}</p>
@endif

// paginate
// posts </nav> 밑에 추가
{{ $posts->onEachSide(1)->links() }}

git commit

git add .
git commit -m "feat: create post store function"
profile
염씨 클론 코딩

0개의 댓글