How to send an event to a particular user? (laravel 5.3) - php

I am building one to one chat with laravel and pusher.I am trying to send event only to the person one is talking to but not able to do so.Event is send to all ,don't know what is the issue.
<ul class="list" id="friend">
#foreach(Auth::user()->friends() as $f)
<li data-friend="{{$f->id}}" class="clearfix" style="cursor: pointer">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/195612/chat_avatar_01.jpg" alt="avatar" />
<div class="about">
<div class="name">{{$f->firstname}}</div>
<div class="status">
<i class="fa fa-circle online"></i> online
</div>
</div>
</li>
#endforeach
</ul>
textarea:
<div class="chat-message clearfix">
<textarea name="message-to-send" id="message-to-send" placeholder ="Type your message" rows="3"></textarea>
<i class="fa fa-file-o"></i>
<i class="fa fa-file-image-o"></i>
<button id="send" data-userid="{{Auth::user()->id}}">Send</button>
</div>
script:
<script>
b={!!json_encode(Auth::user()->id)!!};
pusher=new Pusher('******',{
cluster:'ap1'
});
channel=pusher.subscribe('user'+b);
$(document).ready(function(){
$('#friend li').click(function(){
var f=$(this).attr('data-friend');
$('#send').click(function(){
var userid=$(this).attr('data-userid');
var message=$('#message-to-send').val();
$.ajax({
method:'GET',
url:'/chat2/'+message+'/'+f,
success:function(response){
console.log('dshfgjhgdhjs');
}
})
});
});
});
channel.bind('App\\Events\\chat2', function(e){
console.log(e);
} );
</script>
route:
Route::get('/chat2/{message}/{friend}',function($message,$friend){
event(new chat2(Auth::user(),$message,$friend));
});
event:
class chat2 implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $user;
public $message;
public $friend;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(User $user,$message,$friend)
{
$this->user=$user;
$this->message=$message;
$this->friend=$friend;//
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return new Channel('user'.$this->friend);
}
}

You need to look at private broadcast channels. Laravel supports authenticated private channels for broadcast events.
https://laravel.com/docs/5.4/broadcasting#authorizing-channels
Once you have the user listening on a private channel, you can send events only to that channel.

Related

Laravel websocket real time chat with vue.js

Hi I am trying to build a laravel real time chat. I configured websockets and it seems to be connecting, but now I am trying to send a message and its working but to the other user the message is not displayed unless I refresh the page. I was following a tutorial in youtube did everything like in the tutorial and I dont know why I am receiving this errors. If you can have a look I would appreciate it.
Errors I am receiving
DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/js/utf8.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
ChatsComponent.vue
<template>
<div class="row">
<div class="col-8">
<div class="card card-default">
<div class="card-header">Messages</div>
<div class="card-body p-0">
<ul class="list-unstyled" style="height:300px; overflow-y:scroll">
<li class="p-2" v-for="(message,index) in messages" :key="index">
<strong>{{ message.user.name }}</strong>
{{ message.message }}
</li>
</ul>
</div>
<input
#keyup.enter="sendMessage"
v-model="newMessage"
type="text"
name="message"
placeholder="Enter your message..."
class="form-control">
</div>
<span class="text-muted">User is typing...</span>
</div>
<div class="col-4">
<div class="card card-default">
<div class="card-header">Active Users</div>
<div class="card-body">
<ul>
<li class="py-2">Harish</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:['user'],
data(){
return {
messages:[],
newMessage:'',
}
},
created(){
this.fetchMessages();
Echo.join('chat')
.listen('MessageSent', (event) => {
this.messages.push(event.message);
});
},
methods:{
fetchMessages(){
axios.get('messages').then(response =>{
this.messages = response.data
})
},
sendMessage(){
this.messages.push({
user:this.user,
message:this.newMessage
});
axios.post('messages', {message: this.newMessage});
this.newMessage='';
}
}
}
</script>
Message Model
class Message extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
And I added this to User model
public function messages()
{
return $this->hasMany(Message::class);
}
ChatsController
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
class ChatsController extends Controller
{
public function _construct(){
$this->middleware('auth');
}
public function index()
{
return view('chats');
}
public function fetchMessages()
{
return Message::with('user')->get();
}
public function sendMessages(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' =>'success'];
}
}
MessageEvent event
App\Message; use App\User;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('chat');
}
}
Routes
Route::get('/chats','ChatsController#index')->middleware('auth');
Route::get('/messages','ChatsController#fetchMessages');
Route::post('/messages','ChatsController#sendMessages');
Broadcast::channel('chat', function ($user) {
return $user;
});
Chat view
#extends('layouts.app')
#section('content')
<div class="container">
<chats :user="{{ auth()->user()}}"></chats>
</div>
#endsection

Laravel Pusher 401 Unauthorized

I cannot get my events working on laravel 7.x, pusher, laravel-echo. I have set up everything correctly but still getting 401 error. I have also set up broadcast_driver as pusher in .env file. If anyone can help, I will appreciate.
CommentEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CommentEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $comment;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($comment)
{
$this->comment =$comment;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('comment-channel');
}
public function broadcastAs()
{
return 'newComment';
}
}
CommentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Events\CommentEvent;
use App\Comment;
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 response()->json('ok');
}
}
/routes/channels.php
<?php
use Illuminate\Support\Facades\Broadcast;
/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/
// Broadcast::channel('App.User.{id}', function ($user, $id) {
// return (int) $user->id === (int) $id;
// });
Broadcast::channel('comment-channel', function () {
return true;
});
bootstrap.js
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
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: https://adonisjs.com/docs/4.1/csrf');
}
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
});
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
export const store =new Vuex.Store({
state:{
//stores all the comments in this array//
comments:[]
},
getters:{
//returns the comments array//
comments:state=>{
return state.comments
}
},
mutations:{
//populates the comments array in the state with the comments from the database//
getComments:(state,comments)=>{
state.comments =comments
},
addComment:(state,comment)=>{
state.comments = state.push(comment)
}
},
actions:{
/* gets all the comments from comments endpoint api*/
getComments:({commit})=>{
axios.get(`http://127.0.0.1:8000/api/comments`)
.then(res=>{
//commits getcomments mutation and passes a parameter of comments from the response//
commit('getComments',res.data)
})
.catch(err=>{
console.log(err)
})
},
addComment:({commit},comment)=>{
return new Promise((resolve,reject)=>{
axios.post(`http://127.0.0.1:8000/api/comments`,{
author:comment.author,
content:comment.content
})
.then(res=>{
resolve(res)
}).catch(err=>{
reject(err)
})
})
}
}
})
MainApp.vue
<template>
<div class="container">
<div class="row">
<div class="col">
<div class="card">
<div class="card-body">
<form #keyup.enter="postComment">
<div class="form-group">
<input type="text" class="form-control" placeholder="Author's Name" v-model="comment.author">
</div>
<div class="form-group">
<textarea name="comment" id="" rows="6" class="form-control" v-model="comment.content" >
</textarea>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-success" #click.prevent="postComment">
</div>
</form>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card-body">
<div class="media" v-for="comment in comments" :key="comment.id">
<img class="mr-3" src="https://api.adorable.io/avatars/48/#adorable.io.png" alt="Generic placeholder image">
<div class="media-body">
<h5>{{comment.author}}</h5>
{{comment.content}}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import {store} from '../store';
import {mapGetters} from 'vuex';
import {mapActions} from 'vuex';
export default {
store:store,
data:function(){
return{
comment:{
author:'',
content:''
}
}
},
mounted() {
//calls the action getcomments from store.js//
this.$store.dispatch('getComments');
Echo.channel('comment-channel')
.listen('.newComment', (e)=>{
console.log(e)
})
},
computed:{
//gets the comments array from store.js//
...mapGetters([
'comments'
])
},
methods:{
postComment:function(){
this.$store.dispatch('addComment',this.comment)
.then(res=>{
if(res==='ok'){
console.log('success')
}
}).catch(err=>{
console.log(err)
})
}
}
}
</script>
Make sure to pass $user into the channel route callback. replace this code with your channel route. then you are good to go :)
Broadcast::channel('comment-channel', function ($user) {
return true;
});

laravel resource controller - show method not working $id returning value as 'show'

I am new to laravel and i am working in resource controller CRUD operation.i have done with show function and my front end will get the id from the user and i need to show the details using id. For this i have used resource controller show function . Problem is , how to return the id ? i tried with below formats
http://localhost/sbadmin/public/invoice/invoice/show?12
http://localhost/sbadmin/public/invoice/invoice/show/12
both are returning 404 only.
Can anyone suggest how to write this uri ?
Here is my web.php
<?php
Route::prefix('invoice')->group(function() {
Route::get('/createInvoice', 'Invoice\InvoiceController#getAllInvoiceDetails');
Route::post('/addInvoice', 'Invoice\InvoiceController#addInvoice');
Route::post('/checkPhoneNumberAndFetchData', 'Invoice\InvoiceController#checkPhoneNumberAndReturnData');
Route::resource('invoice', 'Invoice\InvoiceManagementController')->only([
'index', 'show'
]);
Route::get('/searchInvoice','Invoice\InvoiceController#searchInvoice');
Route::get('/viewAllInvoice','Invoice\InvoiceController#viewAllInvoice');
Route::get('/viewInvoicesAsJson','Invoice\InvoiceController#viewInvoicesAsJson');
});
Controller:
namespace Modules\Invoice\Http\Controllers\Invoice;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Modules\Invoice\Entities\Invoice;
class InvoiceManagementController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('invoice::viewinvoices');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//return $id;
$invoices = Invoice::findOrFail($id)->with(['user','events','payments'])->get();
return view('invoice::invoice');
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
/**
* Responds to requests to GET /users/show/1
*/
public function getShow($id)
{
//
}
}
blade.php:
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg-5 d-none d-lg-block bg-register-image"></div>
<div class="col-lg-7">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">Search Invoice</h1>
</div>
<form id="form" onsubmit="return OnSubmitForm();" >
#csrf
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="text" class="form-control form-control-user" name="invoice_id" id="id" placeholder="Enter Invoice number" >
</div>
</div>
<button type="submit" class="btn btn-primary btn-user btn-block">
View Invoice
</button>
<hr>
<a href="index.html" class="btn btn-google btn-user btn-block" hidden="">
<i class="fab fa-google fa-fw"></i> Register with Google
</a>
<a href="index.html" class="btn btn-facebook btn-user btn-block" hidden="">
<i class="fab fa-facebook-f fa-fw"></i> Register with Facebook
</a>
</form>
<div class="text-center" hidden="">
<a class="small" href="forgot-password.html">Forgot Password?</a>
</div>
<div class="text-center" hidden="">
<a class="small" href="login.html">Already have an account? Login!</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="{{ asset('sbadmin/vendor/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('sbadmin/vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<!-- Core plugin JavaScript-->
<script src="{{ asset('sbadmin/vendor/jquery-easing/jquery.easing.min.js') }}"></script>
<!-- Custom scripts for all pages-->
<script src="{{ asset('sbadmin/js/sb-admin-2.min.js') }}"></script>
<script type="text/javascript">
function OnSubmitForm()
{
$('#form').prop('action',"invoice/show/"+$('#id').val());
return true;
}
</script>
For Laravel resource controller actions no need to add the CRUD actions
GET/invoice, mapped to the index() method,
GET /invoice/create, mapped to the create() method,
POST /invoice, mapped to the store() method,
GET /invoice/{id}, mapped to the show() method,
GET /invoice/{id}/edit, mapped to the edit() method,
PUT/PATCH /invoice/{id}, mapped to the update() method,
DELETE /invoice/{id}, mapped to the destroy() method.
And try to access your show route action like this:
http://localhost/sbadmin/public/invoice/invoice/12
You don't need to append show in url.
Route::resource('invoice', 'Invoice\InvoiceManagementController')->only([
'index', 'show'
]);
http://localhost/sbadmin/public/invoice/invoice/show/12 -> remove show from here.
Now you url look like.
http://localhost/sbadmin/public/invoice/invoice/12 -> show method
Here, I elaborate more.
Get | http://localhost/sbadmin/public/invoice/invoice | index method
Post | http://localhost/sbadmin/public/invoice/invoice | store method
get | http://localhost/sbadmin/public/invoice/invoice/12 | show method.
first of all change your prefix in routes to:
Route::group(['prefix' => 'invoice', 'as' => 'invoice.'], function(){
then in your script :
function OnSubmitForm()
{
$('#form').prop('action',"invoice/invoice/"+$('#id').val());
return true;
}
i hope this works.

Laravel 5.8 Trying to get property 'unreadNotifications' of non-object

Working on my friend's code, it seems all features like Post, Tag, Category, etc are working fine. I want to add a feature to upload a pdf and download it from front end. After adding DownloadController and Downloads model, It shows varies errors. Most irritating error is
Trying to get property 'unreadNotifications' of non-object(View: /var/www/html/tes/resources/views/admin/layouts/header.blade.php)
Routes:
//Admin Routes
Route::group(['namespace'=>'Admin'], function (){
Route::get('admin/home','HomeController#index')->name('admin.index');
//Users Routes
Route::resource('admin/user','UserController');
//Roles Routes
Route::resource('admin/role','RoleController');
//permissions Routes
Route::resource('admin/permission','PermissionController');
//Download Manager Routes - CV
Route::resource('admin/cv','Downloadcontroller');
//Post Routes
Route::DELETE('postDeleteSelected','PostController#deleteSelected')->name('deleteSelected');
Route::get('admin/post/remove/{post}','PostController#remove')->name('posts.remove');
Route::get('admin/post/trash','PostController#trashed')->name('posts.trashed');
Route::get('admin/post/recover/{id}','PostController#recover')->name('posts.recover');
Route::get('markAsRead','PostController#markRead')->name('markRead');
Route::resource('admin/post','PostController');
//Tag Routes
Route::resource('admin/tag','TagController');
//Category Routes
Route::resource('admin/category','CategoryController');
//Admin Auth Routes
Route::get('admin-login','Auth\LoginController#showLoginForm')->name('admin.login');
Route::post('admin-login','Auth\LoginController#login');
});
Controller:
namespace App\Http\Controllers\Admin;
use App\Model\admin\admin;
use App\Model\user\Downloads;
use App\Http\Controllers\Controller;
use App\Notifications\TaskCompleted;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;
class Downloadcontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
return view('admin.cv.show');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = new Downloads;
if ($request->file('file')){
$file = $request->file('file');
$filename = time().'.'.$file->getClientOriginalExtension();
$request->file->move('storage/'.$filename);
$data->file = $filename;
}
$data->title = $request->title;
$data->description = $request->description;
$data->uploader = Auth::user()->name;
$data->save();
$users = admin::where('id','3')->get();
Notification::send($users, new TaskCompleted($data));
return redirect(route('cv.index'))->with('toast_success','Post Created Successfully');
}
View: in admin.cv.show, the template extends the admin.layouts.app. and the problematic view is here.
<li class="nav-item dropdown">
<a class="nav-link" data-toggle="dropdown" href="#">
<i class="far fa-bell"></i>
#if (Auth::check())
#if(auth()->user()->unreadNotifications->count())
<span class="badge badge-warning navbar-badge">{{auth()->user()->unreadNotifications->count()}}</span>
#endif
#endif
</a>
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
<span class="dropdown-item dropdown-header">
Mark All as Read
</span>
#foreach(auth()->user()->unreadNotifications as $notification)
<div class="dropdown-divider"></div>
<a href="#" class="dropdown-item" style="background-color: lightgrey">
<p><i class="fas fa-envelope mr-2"></i>{{$notification->data['data']}}
<span class="float-right text-muted text-sm">{{$notification->created_at->diffForHumans()}}</span>
</p>
</a>
#endforeach
#foreach(auth()->user()->readNotifications->take(5) as $notification)
<div class="dropdown-divider"></div>
<a href="#" class="dropdown-item">
<p><i class="fas fa-envelope mr-2"></i>{{$notification->data['data']}}
<span class="float-right text-muted text-sm">3 mins</span>
</p>
</a>
#endforeach
<div class="dropdown-divider"></div>
See All Notifications
</div>
</li>

laravel private chat application

Hello i'm a new developer and in my laravel project i have implemented a real time group chat that uses ajax but now i need a real time chat between users in ajax i have tried many things but none have worken it would be very helpful if you could help me or if could send me a link to a good tutorial
Here's the index of my group chat :
#extends('admin.app')
#section('content')
<div class="container">
<div class="row" style ="padding-top:40px;">
<h3 class="text-center">Welcome {{Auth::user()->FullName}}</h3>
<br/><br/>
<div class="col-md-2">
<p>Users online</p>
#foreach($users as $user)
#if($user->isOnline())
<li>{{$user->FullName}}</li>
#endif
#endforeach
</div>
<div class="col-md-8">
<div class="panel panel-info">
<div class="panel-heading">
Recent Chat
</div>
<div class="panel-body">
<ul class="media-list" id="message">
#foreach($messages as $message )
<li class="media">
<div class="media-body">
<div class="media">
<div class="media-body" >
{{$message->message}}
<br/>
<bold> <small class="text-muted">{{$message->from_name}} |{{$message->created_at}}
</small></bold>
<hr>
</div>
</div>
</div>
</li>
#endforeach
</ul>
<div>
<div class="panel-footer">
<div class="input-group">
<input type="text" name="message" class="form-control" placeholder="Enter Message"/>
{{csrf_field()}}
<input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">
<span class="input-group-btn">
<button type="submit" id="send" class="btn btn-info">Send</button>
</span>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/assets/admin/plugins/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setTimeout(realTime, 2000);
});
function realTime() {
$.ajax({
type:'post',
url:'/chat/get',
data:{
'_token':$('input[name=_token]').val(),
},
success: function (data) {
$('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
for (var i=0; i < data.length; i++){
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
}
},
});
setTimeout(realTime, 2000);
}
$(document).on('click','#send', function (){
$.ajax({
type:'post',
url:'/chat/send',
data:{
'_token':$('input[name=_token]').val(),
'from_name':$('input[name=from_name]').val(),
'message':$('input[name=message]').val(),
},
success: function (data) {
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data.message+'<br/><small class="text-muted">'+data.from_name+'|'+ data.created_at+'</small><hr/></div></div></div></li>');
}
})
$('input[name=message]').val('');
});
</script>
#stop
here are the routes of my group chat:
Route::get('/chat', 'Chat\ChatController#index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController#sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController#getMessage' );
here's my controllers of the group chat:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users=user::all();
$messages=message::all();
return view('admin.chat.index',['messages'=> $messages],compact('users'));
}
public function sendMessage(Request $request){
$send = new Message();
$send ->from_name = $request->from_name;
$send ->message = $request->message;
$send->save();
return response()->json($send);
}
public function getMessage(){
$message = Message::all();
return response()->json($message);
}
here the migration for my gruop chat :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->string('from_name');
$table->text('message');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
Sorry in advance for the bad english and it would very grateful if you could help me or if you could send the link of a good tutorial
You need a live connection for that using a websocket, and you can achieve this with Laravel.
What this does is actually keep the connection between the server and the clients open and allows the server to send data to the clients, not just the other way around. Therefore you are able to send the messages to one of the people in your chat as soon as you receive them from the other participant.
That's called Broadcasting in Laravel, take a look at the documentation here:
https://laravel.com/docs/5.5/broadcasting

Categories