on
Italy
- Get link
- X
- Other Apps
composer global require "laravel/installer=~1.1"laravel new RealtimeChatLaravelserver {
listen 8080;
server_name modulus_app_url;
root /mnt/app/public;
index index.html index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/mnt/home/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_index index.php;
include fastcgi_params;
}
}
We have completed the necessary environment settings to continue with the development. Let's go to the design part.app/ folder by default. In this application, we will perform CRUD operations on messages, and this means we need to create a Message model.Model class, which is an abstract class in the Laravel core package Illuminate\Database\Eloquent. Create a file called Message.php under the app/ folder, and put the following content inside the file:This model will allow us to perform several database-related operations easily. For example, when you perform the following query:it will give you all the messages from the database. However, how does it decide on the table name it will fetch in the result? It uses the$tablevalue in the model class. When you create a new message, it will directly save your message model to themessagestable. We will go into detail about Models in the Controller section.Controller
The controller is the place where your application behavior is defined. We will perform some message-related operations ifChatControllerexists in our application. We will have four endpoints for our application:In order to create a controller, simply create a class under
GET /login: for rendering the login pageGET /chat: for rendering the chat pageGET /messages: for listing the last five messages to display on the chat page when the user first opens itPOST /messages: for saving a new messageApp\Http\Controllersand make that class extend a Laravel-specific classControllerwhich exists inApp\Http\Controllers. When you request the/loginor/chatendpoint, they will render their own templates underresources/views. You can do that by using the following actions.class ChatController extends Controller { public function getLogin() { return view("login"); } public function getChat() { return view("chat"); } public function saveMessage() { if(Request::ajax()) { $data = Input::all(); $message = new Message; $message->author = $data["author"]; $message->message = $data["message"]; $message->save(); Pusher::trigger('chat', 'message', ['message' => $message]); } } public function listMessages(Message $message) { return response()->json($message->orderBy("created_at", "DESC")->take(5)->get()); } }The first and second actions will render specific pages. The third action is for saving messages. In this action, the first request type is checked. If it is an AJAX request, it gets all the request body as an associative array. This array is used to populate the newly-created model Message. Then, thesave()method is directly performed on the model to save the database. Whenever a new message is saved to the database, the same message will be sent to Pusher by triggering themessageevent. When you trigger an event, all the connected clients will be notified. In order to use thePusherclass in your Laravel projects, you can do the following:You are OK with the packages, but what about the Pusher configuration? You need to publish vendors in your projects by using the following command:
- Require Pusher-related packages via
composer require vinkla/pusher.- Add the Pusher package, which is
Vinkla\Pusher\PusherServiceProvider::class, to theconfig/app.php.- Use Pusher classes in your controllers, like
Vinkla\Pusher\Facades\Pusher;, above the controller class.php artisan vendor:publishThis command will create a config fileconfig/pusher.php, and you need to provide the required credentials that you can find in your Pusher dashboard. The config file will be like below:'connections' => [ 'main' => [ 'auth_key' => 'auth_key', 'secret' => 'secret', 'app_id' => 'app_id', 'options' => [], 'host' => null, 'port' => null, 'timeout' => null, ], 'alternative' => [ 'auth_key' => 'your-auth-key', 'secret' => 'your-secret', 'app_id' => 'your-app-id', 'options' => [], 'host' => null, 'port' => null, 'timeout' => null, ], ]The fourth endpoint is for listing the last five messages to display on the chat page for newly-joined users. The magical code is:public function listMessages(Message $message) { return response()->json($message->orderBy("created_at", "DESC")->take(5)->get()); }In this code, theMessagemodel is injected to the action or performing database related operations by using$message. First order messages bycreated_atin descending order, and then take the last five. The result is returned in JSON format by usingresponse()->json(...). We have mentioned about controllers and actions, but how are these actions executed when a user goes to a specific URL? You can add your route configurations to the fileapp/Http/routes.php. You can see an example below:In this usage, the request URI and request method are mapped to the Controller name and the action name. That is all with the controllers. Let's switch to the View part.View
In this section, we have used the Blade template engine provided by Laravel. Actually, there is no template engine stuff in our projects, but if you want to send values from the controller to views, you can directly use this project.We have two view pages:login.blade.phpandchat.blade.php. As you can see, there is a blade keyword inside the view file names to state that this will be used for the Blade template engine.The first one is simply for the login operation, so let's talk about theHowever, we are sending a chat message via AJAX, and there are no tokens in the AJAX request headers. We provide a solution by using the following code snippet:chatpage. In this view file, there are some third-party JavaScript libraries served from a CDN likejQuery,jQuery Cookie,Bootstrap, andPusher. We have a chat form to send messages, and Laravel puts a meta description in the page:$.ajaxSetup({ headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') } });Whenever you send an AJAX request, this token will be put inside the header. In order to listen to the message channel in real time, we have used the following:var pusher = new Pusher('app_id'); var channel = pusher.subscribe('chat'); channel.bind('message', function(data) { var message = data.message; $(".media-list li").first().remove(); $(".media-list").append('
Pusher object with an app_id constructor. And then, a client is subscribed to the channel. Whenever a new event with the name message arrives, a callback function will be executed inside the bind() function. The message list area will be refreshed with the new messages.
Finally, whenever a new user opens the chat page, the last five
messages will be shown in the message list area by the following code:
$.get("/messages", function (messages) {
refreshMessages(messages)
});
You can refer to the source code to analyze the full source code of the view pages.
npm install -g modulus. After successful installation, log in to your Modulus account with the Modulus CLI: modulus login. If you want to log in with GitHub, you can use modulus login --github. modulus project create "RealtimeChatLaravel". You have created an application on the Modulus side. sites-enabled, and put the Nginx configuration we mentioned in the Nginx section above inside this sites-enabled folder. modulus deploy to
start deployment, and it's done! This command will upload your project
files to Modulus, and it will also configure the web server using the
Nginx configuration you put inside the sites-enabled folder. RealtimeChatLaravel running at http://realtimechatlaravel-51055.onmodulus.net/cha. Go to this URL to see a working demo. modulus project logs tail, set an environment variable with modulus env set , etc. You can see the full list of commands by using modulus help.
Comments
Post a Comment