How to implement infinite ajax scroll pagination in Laravel - php

I want to use infinite ajax scroll pagination for my blog, but unfortunately I do not have a result!? I still get this error message : server not responding...
Below the code used.
controller:
$posts =Post::paginate(5);
if ($request->ajax()) {
$view = view('user.list.data', compact('posts'))->render();
return response()->json(['html'=>$view]);
}
return view('user.list.page', compact('posts');
view:
<div class="container">
<h2 class="text-center">Liste poste</h2>
<br/>
<div class="col-md-12" id="post-data">
#include('user.list.data')
</div>
</div>
<div class="ajax-load text-center" style="display:none">
<i class="fa fa-spinner fa-spin" style="color: #dd4b39; font-size:36px"></i>
</div>
<script type="text/javascript">
var page = 1;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
page++;
loadMoreData(page);
}
});
function loadMoreData(page) {
$.ajax({
url: '?page=' + page,
type: "get",
beforeSend: function() {
$('.ajax-load').show();
}
}).done(function(data) {
if(data.html == " ") {
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$("#post-data").append(data.html);
}).fail(function(jqXHR, ajaxOptions, thrownError) {
alert('server not responding...');
});
}
</script>
view data:
#foreach($posts as $post)
<div>
<h3>
{{ $post->title }}
</h3>
<p>{{ $post->description }}</p>
<div class="text-right">
<button class="btn btn-success">Read More</button>
</div>
<hr style="margin-top:5px;">
</div>
#endforeach

Related

Chat with laravel, socket io and redis not transferring messages through private channel

I am building a website with laravel, with chat option available inside it. I am able to store the messages in database as well as display in the sender's screen. But I can't manage to display the messages in receiver side. I am providing my codes as below. I used socket io and redis for the chat option.
server.js :
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http,{
cors: { origin: "*"}
});
const port = process.env.PORT || 6001;
var Redis = require('ioredis');
var redis = new Redis();
var users =[];
http.listen(port, function () {
console.log(`Listening to port ${port}`);
});
redis.subscribe('private-channel', function() {
console.log('subscribed to private channel');
});
redis.on('message', function(channel, message) {
message = JSON.parse(message);
console.log(message);
if (channel == 'private-channel') {
let data = message.data.data;
let receiver_id = data.receiver_id;
let event = message.event;
io.to(`${users[receiver_id]}`).emit(channel + ':' + message.event, data);
}
});
io.on('connection', function (socket) {
console.log('connection');
socket.on("user_connected", function (user_id) {
users[user_id] = socket.id;
io.emit('updateUserStatus', users);
console.log("user connected "+ user_id);
});
socket.on('disconnect', function() {
console.log('disconnected');
var i = users.indexOf(socket.id);
users.splice(i, 1, 0);
io.emit('updateUserStatus', users);
console.log(users);
});
});
controller :
public function companyconversation($userId) {
$users = \DB::table('users')->where([
'usertype'=>'individual',
])->get();
$friendInfo = User::findOrFail($userId);
$myInfo = User::find(Session::get('loginId'));
$company = $myInfo;
//$groups = MessageGroup::get();
$this->data['company'] = $company;
$this->data['users'] = $users;
$this->data['friendInfo'] = $friendInfo;
$this->data['myInfo'] = $myInfo;
$this->data['users'] = $users;
$this->data['userId'] = $userId;
//$this->data['groups'] = $groups;
//dd($users);
return view('company.convo', compact('users','friendInfo','myInfo','company'));
}
view :
<div id="main-content">
<div class="container-fluid">
<div class="block-header">
<div class="row clearfix">
<div class="col-md-6 col-sm-12">
<h1> Messages(Chat) </h1>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">Demo </li>
<li class="breadcrumb-item active" aria-current="page">Messages(Chat) </li>
</ol>
</nav>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12 ">
<div class="card ">
<div class="body" style="height:100%; min-height:700px;">
<div class="chatapp_list">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Search...">
<div class="input-group-append">
<span class="input-group-text"><i class="icon-magnifier"></i></span>
</div>
</div>
<div class="col-md-12">
<div class="users">
<h5>Users</h5>
<ul class="list-group list-chat-item">
#if($users->count())
#foreach($users as $users)
<li class="chat-user-list
#if($users->id == $friendInfo->id) active #endif">
<a href="{{ route('company_conversation', $users->id) }}">
<div class="chat-image media">
{!! makeImageFromName($users->fname,$users->lname) !!}
</div>
<div class="media-body">
<span class="name chat-name">{{$users->fname}}</span>
<!-- <span class="message">offline</span> -->
<span class="badge badge-outline status user-status-icon user-icon-{{$users->id}}"></span>
</div>
</a>
</li>
#endforeach
#endif
</ul>
</div>
</div>
</div>
<div class="chatapp_body">
<div class="col-md-9 chat-section">
<div class="chat-header">
<div class="chat-name font-weight-bold">
{{ $users->fname }}
</div>
</div>
<div class="chat-body" id="chatBody">
<div class="message-listing" id="messageWrapper" style="
border: 1px #ccc solid;
height: 100%;
overflow: hidden;
min-height: 450px;
position: relative;
z-index: 9;
color:#333;
background: #fff;
">
</div>
</div>
<div class="chat-box">
<div class="chat-input border text-secondary bg-white p-3 " id="chatInput" contenteditable="">
</div>
<div class="chat-input-toolbar">
<button title="Add File" class="btn btn-light btn-sm btn-file-upload">
<i class="fa fa-paperclip"></i>
</button> |
<button title="Bold" class="btn btn-light btn-sm tool-items"
onclick="document.execCommand('bold', false, '');">
<i class="fa fa-bold tool-icon"></i>
</button>
<button title="Italic" class="btn btn-light btn-sm tool-items"
onclick="document.execCommand('italic', false, '');">
<i class="fa fa-italic tool-icon"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal Success -->
<div class="modal fade" id="adsuccessModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle"> Successfully Saved </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="text-align: center;">
<span> <i class="fa fa-check-circle-o" style="font-size: 6em; color: #060;"></i> </span>
<h2 style="color: #060;"> Ad Saved Successfully</h2>
<button type="button" class="btn btn-round btn-success">
<i class="fa fa-bars"> Back to Ads Lists </i> </button>
</div>
<span style="font-size: 10px; color: #f00; text-align: center; margin-bottom: 1em;">Note: Your Ad will be automatically expired after 30 days of posted</span>
<div class="modal-footer">
<button type="button" class="btn btn-round btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal END -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous"></script>
<script>
function getCurrentTime() {
return moment().format('h:mm A');
}
function getCurrentDateTime() {
return moment().format('MM/DD/YY h:mm A');
}
function dateFormat(datetime) {
return moment(datetime, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YY h:mm A');
}
function timeFormat(datetime) {
return moment(datetime, 'YYYY-MM-DD HH:mm:ss').format('h:mm A');
}
$(function (){
let $chatInput = $(".chat-input");
let $chatInputToolbar = $(".chat-input-toolbar");
let $chatBody = $(".chat-body");
let $messageWrapper = $("#messageWrapper");
let user_id = "{{ Session::get('loginId') }}";
//console.log(user_id);
let ip_address = '127.0.0.1';
let socket_port = '6001';
let socket = io(ip_address + ':' + socket_port);
let friendId = "{{ $friendInfo->id }}";
socket.on('connection',function() {
socket.emit('user_connected', user_id);
});
socket.on('updateUserStatus', (data) => {
let $userStatusIcon = $('.user-status-icon');
$userStatusIcon.removeClass('text-success');
$userStatusIcon.attr('title', 'Away');
console.log(data);
$.each(data, function (key, val) {
if (val !== null && val !== 0) {
let $userIcon = $(".user-icon-"+key);
$userIcon.addClass('text-success');
$userIcon.attr('title','Online');
}
});
});
$chatInput.keypress(function (e) {
let message = $(this).html();
if (e.which === 13) {
$chatInput.html("");
sendMessage(message);
return false;
}
});
function sendMessage(message) {
let url = "{{ route('send-message') }}";
let form = $(this);
let formData = new FormData();
let token = "{{ csrf_token() }}";
formData.append('message', message);
formData.append('_token', token);
formData.append('receiver_id', friendId);
appendMessageToSender(message);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'JSON',
success: function (response) {
if (response.success) {
console.log(response.data);
}
}
});
}
function appendMessageToSender(message) {
let name = '{{ $myInfo->fname }}';
let image = '{!! makeImageFromName($myInfo->fname,$myInfo->lname) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500" title="'+getCurrentDateTime()+'">\n' +
getCurrentTime()+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
'<div class="message-text">\n' + message +
'</div>\n' +
'</div>';
let newMessage = '<div class="row message align-items-center mb-2">'
+ userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
function appendMessageToReceiver(message) {
let name = '{{ $friendInfo->fname,$friendInfo->lname }}';
let image = '{!! makeImageFromName($friendInfo->fname,$friendInfo->lname) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500" title="'+dateFormat(message.created_at)+'">\n' +
timeFormat(message.created_at)+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
' <div class="message-text">\n' + message.content +
' </div>\n' +
' </div>';
let newMessage = '<div class="row message align-items-center mb-2">'
+userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
socket.on("private-channel:App\\Events\\PrivateMessageEvent", function (message)
{
appendMessageToReceiver(message);
});
});
</script>
Event :
<?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 PrivateMessageEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('private-channel');
}
public function handle() {
}
}
I am expecting the message to appear on the receiver side, but it is not happening.

How to implement AJAX on multiple laravel pagination

I have 2 LARAVEL paginations on one page, know i want to implement AJAX technology in order to achive paginations without reload of entire page. With one pagination ajax works perfectly but i have problems when i want to implement AJAX on second Laravel pagination. Does anyone can help me ?
First pagination
Second pagination
Controller
function successlogin(Request $request)
{
$posts= Post::orderby('created_at', 'desc')->paginate(3, ['*'], 'page_1s');
$documents= Document::orderby('created_at', 'desc')->paginate(2, ['*'], 'page_2s');
if ($request->ajax()) {
return view('presult', compact('posts'));
}
return view('main_page', ['posts'=>$posts,'documents'=>$documents]);
}
main_page
<section id="services">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading" style="color: #d21826; font-weight: bold;">Vijesti</h2>
<hr class="my-4">
</div>
</div>
</div>
<div class="container">
#if(session('deletePost'))
<div class="alert alert-danger" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{{ session('deletePost') }}
</div>
#endif
<div id="tag_container">
#include('presult')
</div>
</div>
</section>
<section class="bg-primary" id="about">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading" style="color: white; font-weight: bold;">Službeni Dokumenti</h2>
<hr class="light my-4">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12 mx-auto text-center">
<div id="table_container" class="table-responsive">
#include('table')
</div>
</div>
</div>
</div>
#if (Auth::user())
Dodaj Vijest
#endif
</section>
ajax_script for pagination
$(window).on('hashchange', function() {
if (window.location.hash) {
var page = window.location.hash.replace('#', '');
if (page == Number.NaN || page <= 0) {
return false;
}else{
getData(page);
}
}
});
$(document).ready(function()
{
$(document).on('click', '.pagination a',function(event)
{
event.preventDefault();
$('li').removeClass('active');
$(this).parent('li').addClass('active');
var myurl = $(this).attr('href');
var page=$(this).attr('href').split('page_1s=')[1];
getData(page);
});
});
function getData(page){
$.ajax(
{
url: '?page_1s=' + page,
type: "get",
datatype: "html"
})
.done(function(data)
{
$("#tag_container").empty().html(data);
location.hash = page;
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
}

Realtime-notifications with ajax

Hello i'm a new developer and in my laravel project i have implemented a real time chat function with ajax but i also want to add a real time notification system with ajax so when a message is written all users are notified for that message it would be very helpful if you could help me
here's my index page :
#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's my routes :
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:
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);
}
Sorry in advanced for the bad english but i am a foreigner
well you have to read this tutorial and implement like this....
https://laracasts.com/discuss/channels/general-discussion/step-by-step-guide-to-installing-socketio-and-broadcasting-events-with-laravel-51
$(window).load(realTime);
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);
},
});
}
}
Try this..

Laravel posting and comments , i cannot comment after i created a new post using ajax

when i refresh the page using the browser everything is working fine i could still comment and i could also add new post but the problem is when i create a new post(which means a post like a facebook post) i cannot comment anymore on any post. here is my Homeview :
<div class="All-Post-Display" id="PostRefresh">
<div class="container">
#foreach($latest as $late)
<div class="row">
<div class="col-md-5 col-md-offset-2">
<div class="outside-pannel">
<div class="person">
<img src="/styleimage/facebook.jpg">
<h2>{{$late->user->name}} {{$late->user->lastname}}</h2><br>
<h4>{{$late->created_at->diffForHumans()}}</h4>
</div>
<div class="body-of-post">
<p>{{$late->body}}</p>
</div>
<div class="like-comment-share">
<form>
<ul>
<li><i class="fa fa-thumbs-up"></i>Like</li>
<li><i class="fa fa-comments-o"></i>Comment</li>
<li><i class="fa fa-share"></i>Share</li>
</ul>
</form>
</div>
<div class="comment-section" >
<div class="total-likes">
<h3>3 likes your post</h3>
</div>
<div class="comment-form">
#foreach($late->comments as $comment)
<div class="display-comments">
<div class="comment-img">
<img src="/styleimage/facebook.jpg">
</div>
<div class="comment-container">
<div class="comment-content">
<a name="postername" href="#">rd</a> <span></span>
<div class="reply-like">
<ul>
<li>Like</li>
<li>Reply</li>
<li><h6>just now</h6></li>
</ul>
</div>
</div>
</div>
</div>
#endforeach
<div>
<div class="commenting-container">
<img src="/styleimage/facebook.jpg">
<textarea rows="1" id="comment-body{{$late->id}}" name="body" placeholder="Write a comment..."></textarea>
<input type="text" name="commentable" id="posting-id{{$late->id}}" value="{{$late->id}}" style="display: none;">
<div class="emojis">
<ul>
<li><i class="fa fa-smile-o"></i></li>
<li><i class="fa fa-camera-retro"></i></li>
<li><i class="fa fa-bookmark"></i></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
$('#comment-body{{$late->id}}').keypress(function (e) {
if (e.which == 13) {
var comment = $('#comment-body{{$late->id}}').val();
var postCommentedId = $('#posting-id{{$late->id}}').val();
$.ajax({
url: '/comment',
type: 'post',
data: {'commentable_id':postCommentedId,'body':comment,'_token':$('input[name=_token]').val()},
success: function (data) {
console.log('success');
$('#comment-body{{$late->id}}').val(null);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('errorThrown');
}
});
}
});
});
</script>
#endforeach
</div>
</div>
</div>
{{csrf_field()}}
<script>
$( document ).ready(function() {
$('#ButtonPost').click(function (event) {
var thebody = $('#bodyPost').val();
$.ajax({
url: 'index',
type: 'post',
data: {'body':thebody,'_token':$('input[name=_token]').val()},
success: function (data) {
$('#PostRefresh').load(location.href + ' #PostRefresh');
$('#bodyPost').val(null);
}
});
});
});
</script>
after running this AJAX at the bottom the AJAX inside my #foreach doesn't work , id="PostRefresh" is gonna be refreshed when i make new post. im also using id="{{id of post}}" to make them unique in every post, Please Help Thank you...
Instead of this
$('#ButtonPost').click(function (event) ...
Try to use
$(document).on('click','#ButtonPost',(function (event) ...
Here the problem is, once you create new DOM then you don't have id of new element created to your jquery id not working.
But with this code you will get jquery code linked to every element of if #buttonPost.

Implement VueJS with Laravel Blade?

I have create a two different feed component with Laravel and vue js, the first one is pure using laravel controller and passing the data to view. Another one is using controller and passing to vue.js file.
But i trying to combine two together since is would be more user friendly for me which is fetching data into view and binding with vue button.
i had tried with this code but having error.Is there possible to do that?
#foreach($feeds as $feed)
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-0">
<div class="panel panel-white post panel-shadow">
<div class="post-heading">
<div class="pull-left image">
<img src="{{$feed->user->avatar}}" class="avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
{{ $feed->user->name }}
made a post.
</div>
<h6 class="text-muted time">{{ $feed->created_at->diffForHumans() }}</h6>
</div>
</div>
<div class="post-description">
<p>{{ $feed->content }}</p>
<div class="stats">
<like id="{{$feed->id}}"></like> <objection id="{{$feed->id}}"></objection>
<a href="#" class="stat-item">
<i class="fa fa-retweet icon"></i>12
</a>
<a href="#" class="stat-item">
<i class="fa fa-comments-o icon"></i>3
</a>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
But the problems is how to passing the id into my vue which is
<like :id="post.id"></like>
<objection :id="post.id"></objection>
Here is my Feed.vue file
<template>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-0">
<div class="panel panel-white post panel-shadow" v-for="post in posts">
<div class="post-heading">
<div class="pull-left image">
<img :src="post.user.avatar" class="avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
{{ post.user.name }}
made a post.
</div>
<h6 class="text-muted time">{{ post.created_at }}</h6>
</div>
</div>
<div class="post-description">
<p>{{ post.content }}</p>
<div class="stats">
<like :id="post.id"></like>
<objection :id="post.id"></objection>
<a href="#" class="stat-item">
<i class="fa fa-retweet icon"></i>12
</a>
<a href="#" class="stat-item">
<i class="fa fa-comments-o icon"></i>3
</a>
</div>
</div>
<comment :id="post.id"></comment>
</div>
</div>
</div>
</div>
<script>
import Like from './Like.vue'
import Comment from './Comment.vue'
import Objection from './Objection.vue'
export default{
mounted(){
this.get_feed()
},
components:{
Like,
Objection,
Comment
},
methods:{
get_feed(){
this.$http.get('/feed')
.then( (response)=>{
response.body.forEach( (post) =>{
this.$store.commit('add_post',post)
})
})
},
},
computed: {
posts(){
return this.$store.getters.all_posts
}
}
}
This is one of my Like components.
<template>
<button class="btn btn-basic" v-if="!auth_user_likes_post" #click="like()">
True {{ likers.length }}
</button>
<button class="btn btn-primary" v-else #click="unlike()">
Untrue {{ likers.length }}
</button>
<script>
export default {
mounted(){
},
props: ['id'],
computed: {
likers() {
var likers = []
this.post.likes.forEach( (like) => {
likers.push(like.user.id)
})
return likers
},
auth_user_likes_post() {
var check_index = this.likers.indexOf(
this.$store.state.auth_user.id
)
if (check_index === -1)
return false
else
return true
},
post() {
return this.$store.state.posts.find( (post) => {
return post.id === this.id
})
}
},
methods: {
like() {
this.$http.get('/like/' + this.id)
.then( (resp) => {
this.$store.commit('update_post_likes', {
id: this.id,
like: resp.body
})
})
},
unlike() {
this.$http.get('/unlike/' + this.id)
.then( (response) => {
this.$store.commit('unlike_post', {
post_id: this.id,
like_id: response.body
})
})
}
}
}
Can you take a look at this https://scotch.io/tutorials/implement-a-favoriting-feature-using-laravel-and-vue-js, might be helpful.
It explains in details how you setup the Model in a proper way, the computed, and methods, also the steps are just too easy to follow.
I noticed that you have:
mounted(){
//blank
}
You could add some functionality like:
mounted() {
this.isFavorited = this.isFavorite ? true : false;
}
This will help handle the toggle part

Categories