瀏覽代碼

Implement article comments

axkuhta 1 年之前
父節點
當前提交
e62ab17006
共有 4 個文件被更改,包括 34 次插入1 次删除
  1. 25 1
      app/Http/Controllers/ArticleController.php
  2. 4 0
      app/Models/Article.php
  3. 4 0
      resources/views/article.blade.php
  4. 1 0
      routes/web.php

+ 25 - 1
app/Http/Controllers/ArticleController.php

@@ -30,7 +30,9 @@ class ArticleController extends Controller
 
 	function view(Article $article) {
 		return view("article", [
-			"article" => $article
+			"article" => $article->load([
+				"comments" => function($query) { $query->recent(); }
+			])
 		]);
 	}
 
@@ -66,6 +68,28 @@ class ArticleController extends Controller
 		return view("success");
 	}
 
+	function comment(Article $article, Request $request) {
+		$request->validate([
+			"name" => "required",
+			"email" => "required|email",
+			"content" => "required"
+		], [
+			"name" => "Укажите ваше имя.",
+			"email" => "Укажите ваш email.",
+			"content" => "Введите комментарий."
+		]);
+
+		$arr = $request;
+
+		$article->comments()->create([
+			"name" => $arr->name,
+			"email" => $arr->email,
+			"content" => $arr->content
+		]);
+
+		return view("success");
+	}
+
 	function drop(Article $article) {
 		$article->delete();
 

+ 4 - 0
app/Models/Article.php

@@ -21,4 +21,8 @@ class Article extends Model
 	function scopePublished($query) {
 		$query->where("status", static::STATUS_PUBLISHED);
 	}
+
+	function comments() {
+		return $this->morphMany(Comment::class, "commentable");
+	}
 }

+ 4 - 0
resources/views/article.blade.php

@@ -7,4 +7,8 @@
 <p>
 	<a href="/article/{{ $article->id }}/edit">Редактировать</a> | <a href="/article/{{ $article->id }}/delete">Удалить</a>
 </p>
+@include("include.comments", [
+	"comment_form_target" => "/article/$article->id/comment",
+	"comments" => $article->comments
+])
 @endsection

+ 1 - 0
routes/web.php

@@ -52,4 +52,5 @@ Route::get('/article/{article}', [Controllers\ArticleController::class, 'view'])
 Route::get('/article/{article}/delete', [Controllers\ArticleController::class, 'drop']);
 Route::get('/article/{article}/edit', [Controllers\ArticleController::class, 'edit']);
 Route::post('/article/{article}/edit', [Controllers\ArticleController::class, 'store']);
+Route::post('/article/{article}/comment', [Controllers\ArticleController::class, 'comment']);
 Route::post('/article/add', [Controllers\ArticleController::class, 'store']);