10. Community store

community_user many to many 관계 테이블 생성

php artisan make:migration create_community_user_table

생성된 migration 파일 수정

Schema::create('community_user', function (Blueprint $table) {
  $table->foreignId('community_id');
  $table->foreignId('user_id');
});

migrate

php artisan migrate

Community 모델 수정

public function users()
{
  return $this->belongsToMany(User::class);
}

유효성 검사 store form request 생성

laravel form request docs

php artisan make:request StoreCommunityRequest

// StoreCommunityRequest.php
public function authorize()
{
  return true;
}

public function rules()
{
  return [
    'name' => 'required|min:3|max:20|unique:communities',
    'description' => 'required|max:500',
  ];
}

Community 컨트롤러 수정

public function store(StoreCommunityRequest $request)
{
  $community = Community::create($request->validated() + ['owner_id' => auth()->id()]);
  $community->topics()->attach($request->topics);

  $community->users()->attach(auth()->id());

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

git commit

git add .
git commit -m "feat: create community store function"

좋은 웹페이지 즐겨찾기