Skip to content

Commit

Permalink
Basic app message with auto broadcasting working.
Browse files Browse the repository at this point in the history
  • Loading branch information
marcoslor committed Dec 11, 2019
1 parent b4cd209 commit b3326f5
Show file tree
Hide file tree
Showing 15 changed files with 125 additions and 41 deletions.
2 changes: 1 addition & 1 deletion .env.testing
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ LOG_CHANNEL=stack
DB_CONNECTION=sqlite
DB_DATABASE=:memory:

BROADCAST_DRIVER=redis
BROADCAST_DRIVER=log
QUEUE_DRIVER=redis
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
Expand Down
1 change: 1 addition & 0 deletions .idea/symfony2.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions app/Chat.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App;

use App\Events\MessageSent;
use Illuminate\Database\Eloquent\Model;

class Chat extends Model
Expand Down Expand Up @@ -33,4 +34,10 @@ public function addUser($user){
$this->users()->syncWithoutDetaching(User::find($user));
}

public function sendMessage($body, $user_id){
$message = Message::create(['body'=>$body, 'chat_id'=>$this->id, 'user_id'=>$user_id]);
broadcast( new MessageSent($message) );
return $message;
}

}
20 changes: 20 additions & 0 deletions app/Events/MessageSent.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,24 @@ public function broadcastOn()
{
return new PrivateChannel('chat.'.$this->message->chat->id);
}

/**
* Get the data to broadcast.
*
* @return array
*/
public function broadcastWith()
{
return [$this->message];
}

/**
* The event's broadcast name.
*
* @return string
*/
public function broadcastAs()
{
return 'message.sent';
}
}
27 changes: 18 additions & 9 deletions app/Http/Controllers/MessagesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,36 @@

class MessagesController extends Controller
{
protected function validateRequest()
protected $rules = [
'body' => 'required',
];

protected function validateRequest($key)
{
return request()->validate([
'body' => 'required',
]);
if ($key)
{
return request()->validate($this->rules)[$key];
}
return request()->validate($this->rules);
}

public function store(Chat $chat)
{
$user = Auth::user();

if($chat->users->contains($user))
if ($chat->users->contains($user))
{
$message = Message::create(array_merge($this->validateRequest(), ['user_id'=> $user->id, 'chat_id'=>$chat->id]));
event( new MessageSent($message) );

$chat->sendMessage($this->validateRequest('body'), $user->id);
return $this->getMessages($chat);

}
}

/**
* Return messages with user object
*
* @param Chat $chat
* @return string
*/
public function getMessages(Chat $chat){
return $chat->messages()->with('user')
->get()
Expand Down
1 change: 0 additions & 1 deletion config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,6 @@
App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,

],

/*
Expand Down
35 changes: 35 additions & 0 deletions database/migrations/2019_12_10_221452_create_failed_jobs_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFailedJobsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('failed_jobs');
}
}
2 changes: 1 addition & 1 deletion laravel-echo-server.lock
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"process": 7237
"process": 2910
}
19 changes: 11 additions & 8 deletions public/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -31236,7 +31236,7 @@ var render = function() {
_c("strong", { staticClass: "primary-font" }, [
_vm._v(
"\n " +
_vm._s(message.user) +
_vm._s(message.user.name) +
"\n "
)
])
Expand Down Expand Up @@ -43812,9 +43812,6 @@ __webpack_require__.r(__webpack_exports__);
__webpack_require__(/*! ./bootstrap */ "./resources/js/bootstrap.js");

window.Vue = __webpack_require__(/*! vue */ "./node_modules/vue/dist/vue.common.js");
Echo["private"]("chat.".concat(window.location.pathname.split("/").pop())).listen('MessageSent', function (e) {
console.log('Info ' + e.update);
});



Expand All @@ -43827,20 +43824,26 @@ var app = new Vue({
messages: []
},
created: function created() {
var _this = this;

this.fetchMessages();
Echo["private"]("chat.".concat(window.location.pathname.split("/").pop())).listen('.message.sent', function () {
_this.fetchMessages();
});
},
methods: {
fetchMessages: function fetchMessages() {
var _this = this;
var _this2 = this;

axios.get(window.location.pathname + '/messages').then(function (response) {
_this.messages = response.data;
_this2.messages = response.data;
});
},
addMessage: function addMessage(message) {
this.messages.push(message);
var _this3 = this;

axios.post(window.location.pathname + '/messages', message).then(function (response) {
console.log(response.data);
_this3.fetchMessages();
});
},
createChat: function createChat() {}
Expand Down
2 changes: 1 addition & 1 deletion public/mix-manifest.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"/js/app.js": "/js/app.js?id=7eec61c90ca0f66bdf69",
"/js/app.js": "/js/app.js?id=771cdedd70192729788a",
"/css/app.css": "/css/app.css?id=2a4461fc35df4e8d0a06"
}
2 changes: 1 addition & 1 deletion resources/js/Components/ChatMessages.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<div class="chat-body clearfix">
<div class="header">
<strong class="primary-font">
{{ message.user }}
{{ message.user.name }}
</strong>
</div>
<p>
Expand Down
19 changes: 10 additions & 9 deletions resources/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@ require('./bootstrap');

window.Vue = require("vue");

Echo.private(`chat.${window.location.pathname.split("/").pop()}`)
.listen('MessageSent', (e) => {
console.log('Info ' + e.update);
});

import ChatMessages from "./Components/ChatMessages";
import ChatForm from "./Components/SendMessage";
import CreateChat from "./Components/CreateChat";
Expand All @@ -15,16 +10,21 @@ Vue.component('chat-messages', ChatMessages);
Vue.component('chat-form', ChatForm);
Vue.component('create-chat', CreateChat);


const app = new Vue({
el: '#app',

data: {
messages: []

},

created() {
this.fetchMessages();

Echo.private(`chat.${window.location.pathname.split("/").pop()}`)
.listen('.message.sent', () => {
this.fetchMessages();
});
},

methods: {
Expand All @@ -35,10 +35,8 @@ const app = new Vue({
},

addMessage(message) {
this.messages.push(message);

axios.post(window.location.pathname+'/messages', message).then(response => {
console.log(response.data);
this.fetchMessages();
});
},

Expand All @@ -47,3 +45,6 @@ const app = new Vue({
}
}
});



9 changes: 4 additions & 5 deletions routes/channels.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@
|
*/

Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
use App\Chat;
use Illuminate\Support\Facades\Auth;

Broadcast::channel('chat.{chatId}', function ($chatId) {
return Chat::get($chatId)->contains(Auth::user);
Broadcast::channel('chat.{chat}', function ($user, Chat $chat) {
return $chat->users->contains(Auth::user());
});

1 change: 1 addition & 0 deletions tests/Feature/ChatManagingTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public function only_a_logged_in_user_can_create_chats(){
* @test
*/
public function a_user_can_send_another_user_a_message(){
$this->withoutExceptionHandling();
$this->actingAs($user = factory('App\User')->create())
->post('/chats', ['title'=>'Chat da empresa', 'users'=>[$user2 = factory('App\User')->create()]]);

Expand Down
19 changes: 14 additions & 5 deletions tests/Unit/MessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

namespace Tests\Unit;

use App\Chat;
use App\Events\MessageSent;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\WithoutEvents;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;

class MessageTest extends TestCase
{
use RefreshDatabase;
/**
* A message must belongs to an user
*
Expand All @@ -27,10 +31,15 @@ public function it_belongs_to_an_user()
*/
public function event_is_broadcasted_when_message_is_sent()
{
broadcast(new MessageSent($message));
$this->assertEventIsBroadcasted(
MessageSent::class,
'private-notification.' . $notification->id
);
Event::fake();

/** @var Chat $chat */
$chat = factory('App\Chat')->create();

$chat->addUser($user = factory('App\User')->create());
$this->actingAs($user);
$chat->sendMessage('hello', $user->id);

Event::assertDispatched(MessageSent::class);
}
}

0 comments on commit b3326f5

Please sign in to comment.