Laravelライブコメントシステムを構築する

公開: 2021-09-22

オンラインコミュニティやブログへの信頼を築くために必要な重要な要素の1つは、適切に設計されたLaravelライブコメントシステムです。

ただし、DisqusやCommentoなどの自己ホスト型のコメントシステムに依存しない限り、最初の試行で正しく理解するのは簡単ではありません。それぞれに独自の欠点があります。 彼らはあなたのデータを所有し、限られたデザインとカスタマイズを提供します、そして最も重要なことに、彼らは無料ではありません。

これらの制限があるため、リアルタイムのコメントシステムを構築するというアイデア(データを制御し、ブログに合うようにルックアンドフィールを設計およびカスタマイズするという利点があります)が魅力的な場合は、読み続けてください。

この記事では、さまざまなコメント機能を備えた、適切に設計されたリアルタイムのコメントシステムを開発する方法について説明します。 Vue.jsとSocket.ioを使用してリアルタイムチャットアプリケーションを構築するという原則に従い、Laravel、Pusher、およびReactを使用してリアルタイムコメントシステムを開発します。

飛び込みましょう!

構築するもの

コミュニティへの信頼を築くために、任意のWebサイトやブログに統合できるリアルタイムのコメントシステムを構築します。

オンラインコミュニティやブログへの信頼を築くために必要な重要な要素の1つは、適切に設計されたLaravelライブコメントシステムです。 ここから始める方法を学ぶクリックしてツイート

ビルディングブロックの概要:Laravel、Pusher、Vue

開発に取り掛かる前に、リアルタイムコメントシステムの開発に使用するテクノロジーについて説明しましょう。

Laravel

LaravelはオープンソースのMVC指向のPHPフレームワークです。 エレガントな構文で知られる単純なものから複雑なものまでのPHPWebアプリケーションを構築するために使用されます。 このコメントシステムを構築するためにLaravelが不可欠なものを学ぶ。

プッシャー

プッシャーを使用すると、開発者はリアルタイムの機能を大規模に作成できます。 この記事では、Laravel Echoを組み合わせて、Pusherサーバーへのリアルタイムブロードキャストイベントを作成し、Vue.jsを使用してフロントエンドにコンテンツを表示します。

Vue.js

Vue.jsは、私たちが選択したフロントエンドフレームワークです。 Vue.jsはプログレッシブJavaScriptフロントエンドフレームワークであり、フロントエンド開発への習得が容易でわかりやすいアプローチで知られています。 Vue.jsを使用して、リアルタイムのコメントシステムを開発します。

コメントシステムの構築

上で概説したコメントシステムがあなたが望むもののように聞こえる場合は、それを構築することに移りましょう。

1. Laravel、Pusher、Echoをインストールしてセットアップします

LaravelがPusherと完全に連携するように設定および構成することで、Laravelがすべてのバックグラウンドタスクを実行したため、Laravel、Echo、およびPusherのインストールとセットアップは簡単です。

まず、バックエンドのPHPフレームワークであるLaravelをインストールして構成することから始めます。 Laravel CLIをグローバルにインストールしている場合は、このコマンドを使用してLaravelの新しいインスタンスを取得できます。

 laravel new commenter

新しいLaravelインスタンスはcommenterというフォルダーにインストールされます。 VSCodeでフォルダーを開き、ターミナルでそのフォルダーに移動しましょう。

 cd commenter code .

開発サーバーを起動する前に、プロジェクトで使用されるいくつかの必要なパッケージをインストールして構成しましょう。

次のコマンドを実行して、PusherPHPSDKをインストールします。

 composer require pusher/pusher-php-server

次のコマンドを実行して、Vue.jsフロントエンドに必要なNPMパッケージをインストールします。

 npm install --save laravel-echo pusher-js

次に、LaravelEchoとPusherを構成します。 resources / js / bootstrap.jsファイルを開き、次のスクリプトを貼り付けます。

 window._ = require("lodash"); window.axios = require("axios"); window.moment = require("moment"); window.axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"; window.axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; window.axios.defaults.headers.common.crossDomain = true; window.axios.defaults.baseURL = "/api"; let token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { window.axios.defaults.headers.common["X-CSRF-TOKEN"] = token.content; } else { console.error("CSRF token not found"); } /** * Echo exposes an expressive API for subscribing to channels and listening * for events that Laravel broadcasts. Echo and event broadcasting * allows your team to build robust real-time web applications quickly. */ import Echo from "laravel-echo"; window.Pusher = require("pusher-js"); window.Echo = new Echo({ broadcaster: "pusher", key: process.env.MIX_PUSHER_APP_KEY, cluster: process.env.MIX_PUSHER_APP_CLUSTER, forceTLS: true });

上記のスクリプトから、Axiosインスタンスをデフォルト構成で構成していることがわかります。 次に、Pusherとその構成を使用するようにLaravelEchoを構成します。

2.データベースのセットアップと移行

次に、永続化のためにコメントを保存するデータベースを作成して設定します。 SQLiteを使用しますが、任意のデータベースクライアントを使用できます。

データベースフォルダー内にdatabase.sqliteファイルを作成し、次のように.envファイルを更新します。

 DB_CONNECTION=sqlite DB_DATABASE=/Users/all/paths/to/project/commenter_be/database/database.sqlite DB_HOST=127.0.0.1 DB_PORT=3306 DB_USERNAME=root DB_PASSWORD=

次に、このコマンドを実行してコメント移行を作成し、次のスクリプトで更新します。

 php artisan make:migration create_comments_table

database / migrations / xxxx_create_comments_table_xxxx.phpファイルを開き、次のコードを貼り付けます。

 <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCommentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('comments', function (Blueprint $table) { $table->id(); $table->string('content'); $table->string('author'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('comments'); } }

これにより、新しいコメントデータベーステーブルが作成され、コンテンツと作成者の列が追加されます。

最後に、移行を作成するには、次のコマンドを実行します。

 php artisan migrate

3.モデルの作成

Laravelでは、モデルが重要です。モデルは、データベースと通信してデータ管理を処理するための最も確実な方法です。

Laravelでモデルを作成するには、次のコマンドを実行します。

 php artisan make:model Comment

次に、 app / models / Comment.phpファイルを開き、次のコードを貼り付けます。

 <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Comment extends Model { use HasFactory; protected $fillable = ['content', 'author']; } $ fillable配列を使用すると、モデルをまとめて作成および更新できます。

4.コントローラーの作成

コントローラーは、アプリケーションのすべてのロジック、ビジネス、その他を収容するため重要です。そこで、コメントロジックを処理するコントローラーを作成しましょう。

php artisan make:controller CommentController

次に、 app / Http / Controllers / CommentController.phpファイルを開き、次のコードを貼り付けます。

 <?php namespace App\Http\Controllers; use App\Models\Comment; use App\Events\CommentEvent; use Illuminate\Http\Request; class CommentController extends Controller { // public function index() { return view('comments'); } public function fetchComments() { $comments = Comment::all(); return response()->json($comments); } public function store(Request $request) { $comment = Comment::create($request->all()); event(new CommentEvent($comment)); return $comment; } }

コントローラには、コメントビューを返す、すべてのコメントをフェッチする、新しいコメントを保存するという3つの異なるメソッドがあります。 最も重要なことは、新しいコメントを保存するたびにイベントを発生させ、フロントエンドがリッスンして、PusherとLaravelEchoを使用して関連するページを新しいコメントでリアルタイムに更新することです。

5.ルートの作成

ルートを適切に構成するには、多くのファイルを更新する必要があるので、始めましょう。

まず、routesフォルダーのapi.phpファイルを更新します。 ファイルを開き、次のコードを追加します。

 use App\Http\Controllers\CommentController; //... Route::get('/', [CommentController::class, 'index']); Route::get('/comments', [CommentController::class, 'fetchComments']); Route::post('/comments', [CommentController::class, 'store']);

次に、同じフォルダーにあるchannels.phpファイルを開き、次のコードを追加して、以前に発生したイベントを承認します。

 Broadcast::channel('comment', function ($user) { return true; });

次に、同じフォルダーにあるweb.phpファイルを開き、次のコードを追加して、リクエストをホームページにリダイレクトします。ホームページで、Vue.jsがリクエストを取得します。

 use App\Http\Controllers\CommentController; //... Route::get('/', [CommentController::class, 'index']);

最後に、 comments.blade.phpという名前のresources / viewsフォルダーに新しいブレードファイルを作成し、次のコードを追加します。

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Commenter</title> <meta name="csrf-token" content="{{ csrf_token() }}"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css" /> <style> .container { margin: 0 auto; position: relative; width: unset; } #app { width: 60%; margin: 4rem auto; } .question-wrapper { text-align: center; } </style> </head> <body> <div> <div class="container"> <div class="question-wrapper"> <h5 class="is-size-2"> What do you think about <span>Dogs</span>?</h5> <br> <a href="#Form" class="button is-medium has-shadow has-text-white">Comment</a> </div> <br><br> <comments></comments> <new-comment></new-comment> </div> </div> <script async src="{{mix('js/app.js')}}"></script> </body> </html>

スクリプトは、投稿タイトルとVueコンポーネントを追加して、上で作成した投稿タイトルに新しいコメントを表示および追加します。

次のコマンドを実行して、すべてが正しく取得されるかどうかをテストします。

 npm run watch php artisan serve

このページが表示されたら、この記事の次のステップに進む準備ができています。

競争力を高めるホスティングソリューションが必要ですか? Kinstaは、信じられないほどの速度、最先端のセキュリティ、および自動スケーリングであなたをカバーします。 私たちの計画をチェックしてください

Laravelのライブコメントシステム
Laravelのライブコメントシステム

6. Vueのセットアップ(フロントエンド)

この投稿に加えられたすべてのコメントを作成して表示するために、Vueインスタンスを作成して設定します。

まず、Vuexストアのセットアップから始めます。 resource / js/storeフォルダーに次のファイルを作成します。

コメント状態の作成

アクション.jsを作成し、次のコードを追加します。

 let actions = { ADD_COMMENT({ commit }, comment) { return new Promise((resolve, reject) => { axios .post(`/comments`, comment) .then(response => { resolve(response); }) .catch(err => { reject(err); }); }); }, GET_COMMENTS({ commit }) { axios .get("/comments") .then(res => { { commit("GET_COMMENTS", res.data); } }) .catch(err => { console.log(err); }); } }; export default actions;

アクションファイルは、バックエンドのコメントエンドポイントを呼び出します。

次に、getters.jsファイルを作成し、次のコードを追加します。

 let getters = { comments: state => { return state.comments; } }; export default getters;

Getterファイルは、状態内のすべてのコメントを取得するために使用されます。

mutations.jsファイルを作成し、次のコードに貼り付けます。

 let mutations = { GET_COMMENTS(state, comments) { state.comments = comments; }, ADD_COMMENT(state, comment) { state.comments = [...state.comments, comment]; } }; export default mutations;

次に、state.jsファイルを作成し、次のコードに貼り付けます。

 let state = { comments: [] }; export default state;

最後に、Vueインスタンスにエクスポートされたindex.jsファイルにすべてを追加し、index.jsファイルを作成して、以下を追加します。

 import Vue from "vue"; import Vuex from "vuex"; import actions from "./actions"; import mutations from "./mutations"; import getters from "./getters"; import state from "./state"; Vue.use(Vuex); export default new Vuex.Store({ state, mutations, getters, actions });

コンポーネントを作成する

最後に、コメントコンポーネントを作成して、新しいコメントを表示および追加します。 単一のコメントコンポーネントを作成することから始めましょう。

componentsという名前のresource/jsフォルダーにフォルダーを作成し、 comment.vueを追加して、次のコードを追加します。

 <template> <li class="comment-wrapper animate slideInLeft"> <div class="profile"> </div> <div class="msg has-shadow"> <div class="msg-body"> <p class="name"> {{ comment.author }} <span class="date">{{ posted_at }}</span> </p> <p class="content">{{ comment.content }}</p> </div> </div> </li> </template> <script> export default { name: "Comment", props: ["comment"], computed: { posted_at() { return moment(this.comment.created_at).format("MMMM Do YYYY"); }, }, }; </script> <style lang="scss" scoped> .comment-wrapper { list-style: none; text-align: left; overflow: hidden; margin-bottom: 2em; padding: 0.4em; .profile { width: 80px; float: left; } .msg-body { padding: 0.8em; color: #666; line-height: 1.5; } .msg { width: 86%; float: left; background-color: #fff; border-radius: 0 5px 5px 5px; position: relative; &::after { content: " "; position: absolute; left: -13px; top: 0; border: 14px solid transparent; border-top-color: #fff; } } .date { float: right; } .name { margin: 0; color: #999; font-weight: 700; font-size: 0.8em; } p:last-child { margin-top: 0.6em; margin-bottom: 0; } } </style>

次に、同じフォルダーにcomments.vueという名前の次のファイルを作成し、次のコードを追加します。

 <template> <div class="container"> <ul class="comment-list"> <Comment :key="comment.id" v-for="comment in comments" :comment="comment" ></Comment> </ul> </div> </template> <script> import { mapGetters } from "vuex"; import Comment from "./Comment"; export default { name: "Comments", components: { Comment }, mounted() { this.$store.dispatch("GET_COMMENTS"); this.listen(); }, methods: { listen() { Echo.channel("comment").listen("comment", (e) => { console.log(e); this.$store.commit("ADD_COMMENT", e); }); }, }, computed: { ...mapGetters(["comments"]), }, }; </script> <style scoped> .comment-list { padding: 1em 0; margin-bottom: 15px; } </style>

最後に、 NewComment.vueというファイルを作成し、次のコードを追加します。

 <template> <div class="box has-shadow has-background-white"> <form @keyup.enter="postComment"> <div class="field has-margin-top"> <div class="field has-margin-top"> <label class="label">Your name</label> <div class="control"> <input type="text" placeholder="Your name" class="input is-medium" v-model="comment.author" /> </div> </div> <div class="field has-margin-top"> <label class="label">Your comment</label> <div class="control"> <textarea name="comment" class="input is-medium" autocomplete="true" v-model="comment.content" placeholder="lorem ipsum" ></textarea> </div> </div> <div class="control has-margin-top"> <button :class="{ 'is-loading': submit }" class="button has-shadow is-medium has-text-white" :disabled="!isValid" @click.prevent="postComment" type="submit" > Submit </button> </div> </div> </form> <br /> </div> </template> <script> export default { name: "NewComment", data() { return { submit: false, comment: { content: "", author: "", }, }; }, methods: { postComment() { this.submit = true; this.$store .dispatch("ADD_COMMENT", this.comment) .then((response) => { this.submit = false; if (response.data) console.log("success"); }) .catch((err) => { console.log(err); this.submit = false; }); }, }, computed: { isValid() { return this.comment.content !== "" && this.comment.author !== ""; }, }, }; </script> <style scoped> .has-margin-top { margin-top: 15px; } </style>

次に、 app.jsファイルを開き、次のコードを追加して、前に作成したVueコンポーネントを登録します。

 // resource/js/app.js require("./bootstrap"); window.Vue = require("vue"); import store from "./store/index"; Vue.component("comment", require("./components/Comment")); Vue.component("comments", require("./components/Comments")); Vue.component("new-comment", require("./components/NewComment")); const app = new Vue({ el: "#app", store });
独自のパーソナライズされたコメントシステムを構築したいですか? この投稿には、始めるために必要なものがすべて含まれていますクリックしてツイート

概要

以上です! Laravelを使用してサイトのライブコメントシステムを構築する方法を学びました。

コミュニティやブログへの信頼を築くために、コメントシステムを作成して管理することのメリットについて説明しました。 また、さまざまなコメント機能を利用して、適切に設計されたリアルタイムのコメントシステムをゼロから開発する方法についても検討しました。

このプロジェクトのソースコードは、このGithubリポジトリに複製できます。

私たちが一緒に構築したLaravelライブコメントシステムについてどう思いますか? コメントで教えてください!