I trying to create CHAT in fresh Laravel 6.0 framework.
I following this tutorial https://pusher.com/tutorials/chat-laravel
Routes file, web.php
Route::get('messages', 'ChatsController#fetchMessages');
Route::post('messages', 'ChatsController#sendMessage');
JavaScript files
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
import Pusher from 'pusher-js';
Echo.private('chat').listen('MessageSent', (e) => {
this.messages.push({
message: e.message.message,
user: e.user
});
});
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'xxxxxx',
cluster: 'eu',
encrypted: false,
useTLS: false
});
const app = new Vue({
el: '#app',
data: {
messages: []
},
created() {
this.fetchMessages();
},
methods: {
fetchMessages() {
axios.get('messages').then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.push(message);
axios.post('messages', message).then(response => {
console.log(response.data);
});
}
}
});
BroadcastServiceProvider.php
class BroadcastServiceProvider extends ServiceProvider
{
public function boot()
{
Broadcast::routes();
Broadcast::channel('chat', function ($user) {
return Auth::check();
});
}
}
MessageSent.php Event
public function broadcastOn()
{
return new PrivateChannel('chat');
}
MySQL input works but fetch on another browser NO!
There is Error 500 in Console Log
POST http://localhost:8000/messages 500 (Internal Server Error)<br>
Uncaught (in promise) Error: Request failed with status code 500<br>
at createError (createError.js?2d83:16)<br>
at settle (settle.js?467f:17)<br>
at XMLHttpRequest.handleLoad (xhr.js?b50d:59)<br>
There is fresh laravel log file: https://pastebin.com/vnjNUd2n
Related
I keep getting 404 error when I try to submit the form even though the routes are correctly placed in api.php.Can somebody please help??
const url = "/api/add-feedback";
const token = process.env.MIX_REACT_APP_API_TOKEN;
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [review, setReview] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
const data = {
name: name,
email: email,
review: review
}
const res = await axios.post(url, data, {
headers: {
Authorization: "Bearer " + token,
},
});
if (res.data.status === 200) {
console.log(res.data.message);
}
}
Here is the route in api.php
Route::post('/add-feedback',[ApiController::class,'feedback']);
Here is the ApiController function
public function feedback(Request $res)
{
$data = $res->validate([
'name'=>'required',
'email'=>'required|email',
'review'=>'required'
]);
Feedback::create($data);
return response()->json([
'status' => 200,
'message' => 'Feedback Added Successfully'
]);
}
This is the error I get:
app.js:3415 POST http://127.0.0.1:8000/api/add-feedback 404 (Not Found)
app.js:3880 Uncaught (in promise) Error: Request failed with status code 404
The error is you're using promises with axios, modify your code to something like this:
axios.post(url, data,{
headers: {
Authorization: "Bearer " + token,
},
})
.then((response) => {
if (res.data.status === 200) {
console.log(res.data.message);
}
}, (error) => {
console.log(error);
});
This will send a post request to your route with the data specified.
I am sending data from clinet.php file and can not get data in client.js and always showing user disconnected. What can be reason?
clinet.php
use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version2X;
$client = new Client(new Version2X('http://localhost:9009', [
'headers' => [
'X-My-Header: websocket rocks',
'Authorization: Bearer 12b3c4d5e6f7g8h9i'
]
]));
$client->initialize();
$client->emit('user', ['foo' => 'bar']);
$client->close();
server.js
const server = require('http').createServer();
const io = require("socket.io")(server);
io.on('connection', function (socket) {
socket.on('listen', function (data) {
console.log('client connected');
io.emit('user', {name: 'Marcelo Aires'});
});
// If some user disconnect
socket.on('disconnect', function () {
console.log('user disconnected');
})
});
server.listen(9009);
client.js
var socket = io('http://localhost:9009');
socket.on('user', function (data) {
console.log(data);
});
I have a problem following this tutorial to implement a simple chat in Laravel using Pusher and Vue.js: Link tutorial.
My app.js file in assets/js where I make the request is this one:
const app = new Vue({
el: '#app',
data: {
tweets: []
},
created() {
this.showTweets();
Echo.private('chat')
.listen('TweetSentEvent', (e) => {
this.tweets.push({
tweet: e.tweet.tweet,
user: e.user
});
});
},
methods: {
showTweets() {
axios.get('/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('tweets', tweet).then(response => {
console.log(response.data);
});
}
}
});
My web.php routes:
Auth::routes();
Route::get('/', 'TweetController#index');
Route::get('tweets', 'TweetController#showTweets')-
>middleware('auth');
Route::post('tweets', 'TweetController#sentTweet
My controller is this one:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('chat');
}
public function showTweets(){
return Tweet::with('user')->get();
}
public function sendTweet(Request $request){
$user = Auth::user();
$tweet = $user->tweets()->create([
'tweet' => $request->input('tweet')
]);
broadcast(new TweetSentEvent($user, $tweet))->toOthers();
//return ['status' => 'Tweet Sent!'];
}
When I'm running the app and I try to send a tweet through a POST request clicking on my send button, this error apperas on the console:
POST http://localhost/youChat/public/tweets 500 (Internal Server Error)
Uncaught (in promise) Error: Request failed with status code 500
at createError (app.js:13931)
at settle (app.js:35401)
at XMLHttpRequest.handleLoad (app.js:13805)
Everything seems to be fine... Any help? Thanks in advance!!
have a nice day !
I have a problem:
I set up Laravel Echo & Pusher but got this error, have no idea to resolve :(
I checked my app-key, app-cluster but all are correct.
Can someone help me?
app.js
const app = new Vue({
el: '#app',
data: {
messages: []
},
methods:{
addMessage(message){
this.messages.push(message);
axios.post('/messages', message).then(response => {
console.log(response);
});
}
},
created(){
axios.get('/messages').then(response => {
this.messages = response.data;
});
Echo.channel('chatroom')
.listen('MessageEvent', (e) => {
console.log(e);
});
}
})
bootstrap.js
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: '************',
cluster: 'ap1',
encrypted: false
});
MessageEvent
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message, $user;
public function __construct(Message $message, User $user)
{
$this->message = $message;
//query
$this->user = $user;
}
public function broadcastOn()
{
return new PresenceChannel('chatroom');
}
channels.php
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('chatroom', function ($user, $id) {
return $user;
});
Error 403 or 500 /broadcasting/auth with Laravel version > 5.3 & Pusher, you need change your code in resources/assets/js/bootstrap.js with
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your key',
cluster: 'your cluster',
encrypted: true,
auth: {
headers: {
Authorization: 'Bearer ' + YourTokenLogin
},
},
});
And in app/Providers/BroadcastServiceProvider.php change by
Broadcast::routes()
with
Broadcast::routes(['middleware' => ['auth:api']]);
or
Broadcast::routes(['middleware' => ['jwt.auth']]); //if you use JWT
it worked for me, and hope it help you.
Remove the $id as you are not passing from the event
Broadcast::channel('chatroom', function ($user) {
return true;
});
I think you need to give an authentic point if u have used laravel echo just goto
Resources/assets/js/bootstrap.js
Just add the following line inside the window
Echo = new Echo({
authEndpoint : 'http://localhost/projectName/public/broadcasting/auth',
});
if you're working on localhost make sure that your .env file is set up properly
try setting
APP_URL=http://localhost
DB_HOST=localhost
and run
php artisan config:cache
hope this will help you.
In my laravel application i am using laravel ECHO. In this I'm trying to listen a event "pusher:subscribe" through on method. But I its not happening. I can able to subscribe, add_memeber, remove_memeber as per laravel echo documentation. But i cannot able to listen specifically "pusher:subscribe" event. Actually I am trying to get data from this event and i will manipulate further
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'myKeyHere',
authEndpoint: 'pusher/auth',
auth: {
headers: {
},
params: {
username: this.username
}
}
});
window.Echo.join('openChat').here((users) => {
console.log(users);
}).listen('MessagePublished', (e) => {
console.log('Message Received');
}).on('pusher:subscribe', (users) => {
console.log('NOT WORKING');
}).joining((user) => {
console.log('User Joined');
}).leaving((user) => {
console.log('User gone');
});
After a deep lookup in documents and forums i understood pusher:subscribe is a internal event , so it cannot be captured through Laravel ECHO. But I used pusher:subscription_succeeded to capture the member info ..
Modified Code:
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'myKeyHere',
authEndpoint: 'pusher/auth',
auth: {
headers: {
},
params: {
username: this.username
}
}
});
window.Echo.join('openChat').here((users) => {
console.log(users);
}).listen('MessagePublished', (e) => {
console.log('Message Received');
}).on('pusher:subscription_succeeded', (member) => {
console.log(member);
}).joining((user) => {
console.log('User Joined');
}).leaving((user) => {
console.log('User gone');
});