Laravel/VueJs. How can I display button with different color based on column value passed in? - laravel

I'm looping through user table. And each user table has a button that toggle(update:Boolean type) user status on user table. And I want the button for each user to have red color when the status value for the user is 0 and green when the status is 1. Also I want the button to change the color(LIVE) based on the status value each time it clicked.
component: ToggleStatus.vue
<template>
<div>
<button type="button" v-bind:class="buttonStatus" #click="goOnline">
<span class="ion-ios-wifi" ></span>
</button>
</div>
</template>
<script>
export default {
props: ['userId', 'onlinestat'],
mounted() {
console.log('Component mounted.')
},
data: function() {
return {
status: this.onlinestat,
}
},
methods: {
goOnline() {
axios.post('/reservation/online/' + this.userId )
.then(response => {
this.status =! this.status;
console.log(response.data);
})
.catch(errors => {
if (errors.response.status == 401){
window.location = '/login';
}
});
}
},
computed: {
buttonStatus() {
return(this.status) ? 'btn btn-outline-danger text-danger' : 'btn btn-success ';
}
}
}
</script>
Controller:
$authUser = Auth::user()->business_id;
$employee = User::where('business_id', $authUser)->get()->sortBy('name');
return view('backend.reservation.index', compact('employee'));
View/Blade
<div class="container-fluid flex-grow-1 container-p-y">
<div class="uikit-example">
<div class="row">
#foreach ($employee as $key => $emp)
<div class="col-lg-4 col-md-4 col-sm-12">
<div class="card mb-4">
<div class="card-body">
<div class="media align-items-center">
<img src="{{ asset('Upload/Images/Media/Avatar/Thumb/'.$emp->image) }}" alt class="ui-w-60 rounded-circle">
<div class="media-body pt-2 ml-3">
<h5 class="mb-2">{{ $emp->name }}</h5>
<div class="text-muted small mb-2">{{ $emp->phone }}</div>
<div class="text-muted small mb-2">{{ $emp->email }}</div>
<div class="text-muted small mb-2"><span>ID: </span>{{ $emp->user_code }}</div>
</div>
<div class="">
<toggleonline user-id="{{ $emp->id }}" onlinestat="{{ $emp->onlinestatus }}"></toggleonline>
</div>
</div>
</div>
<div class="card-footer text-center py-3">
{{-- + Go Online --}}
{{-- <span class="ion ion-md-mail"></span> --}}
{{-- <div class="float-right"> --}}
My Reservations
{{-- </div> --}}
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
The result I'm getting is that the button does toggle but the toggle button of all the user come red after on refresh page or when the page loads.

try
buttonStatus() {
return(this.status==0) ? 'btn btn-outline-danger text-danger' : 'btn btn-success ';
}

Related

How to fetch next record from DB when a user submits Answer or Time is finished in laravel 8?

Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Events extends Model
{
use HasFactory;
use SoftDeletes;
public function EventQues()
{
return $this->hasMany(Questions::class, 'event_id')->limit(1);
}
}
Controller
public function ActiveEvent()
{
$display = Events::where('status', 1)->with('EventQues')->first();
// $next = Questions::where('id', '>',$request->id)->where('is_deleted',0)->first('id');
return view('frontend.index', compact('display'));
}
// function for front send answer value to DB
public function getData(Request $request)
{
$value = $request->all();
return response()->json($value, 200);
}
view
#extends('frontend.master')
#section('title', 'Home')
#section('content')
{{-- top menu Start --}}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand text-uppercase font-weight-bold" href="#">Logo</a>
<div class="col-2">
<h5 class=" dropdown-toggle text-light" id="navbarDropdownMenuLink" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">{{ Auth::user()->name }}</h5>
<div class="dropdown-menu mt-1" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="{{ route('twitch.logout') }}">Log Out</a>
</div>
</div>
</div>
</nav> {{-- top menu end --}}
<div class="container-fluid">
<div class="row">
<div class="card shadow col-lg-8 col-md-8 col-sm-12 m-4">
<div class="card-body ">
<div id="twitch-embed"></div>
</div>
</div>
<div class="card shadow col-lg-3 col-md-3 col-sm-12 m-4">
<div class="card-body">
<div id="list-example" class="list-group mt-2">
#if (!$display)
<h2 class="font-weight-bold mt-5" id="Nothing">Currently No Event Is Active</h2>
#else
<h3 class="font-weight-bold p-2 text-light text-center bg-primary">{{ $display->title }}</h3>
<p class="text-justify">{{ $display->description }}</p>
{{-- Displaying questions of Active event from database --}}
<h4 class="text-center p-2">Time :<span id="timer"> </span></h4>
#foreach ($display->EventQues as $data)
<div id="quesDiv"></div>
<div id="quesDiv1">
<h5 id="question">{{ $data->question }}</h5>
<form >
#csrf
<div class="btn btn-group-toggle d-flex flex-column" id="radioDiv"
data-toggle="buttons">
<label class="btn btn-secondary mb-2">
<input type="radio" name="options" id="option_a1" class="answer-check-box"
autocomplete="off" data-value="1"> Yes
</label>
<label class="btn btn-secondary">
<input type="radio" name="options" id="option_a2" class="answer-check-box"
autocomplete="off" data-value="2"> NO
</label>
</div>
</form>
</div>
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
#include('frontend.script')
#endsection
Script.js
$('#option_a1,#option_a2').click(function() {
if (options = $("input[type='radio']:checked")) {
val = options.attr('data-value');
} else if (options = $("input:checkbox:not(:checked)")) {
val = "";
}
});
let interval = setInterval(req, 1000);
function req() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if (val || timeleft < '0') {
$.ajax({
type: "post",
url: "{{ route('ajax') }}",
data: {
'id': '{{ $data->id }}',
'value': val
},
success: function(data) {
$('#quesDiv1').hide();
$('#quesDiv').html('Next Question');
},
error: function(data) {
console.log('error!!')
}
});
var timeOut = setTimeout(interval, 1000);
}
// clearInterval(interval);
}
I am making an app where I have made one to many relation between events and questions. When an event is active questions related to this event are displayed one at a time and when a user submits an answer then fetch the next question from Database. And I was using Ajax call for this.

Ajax call route laravel not found

i want to make delete confirmation laravel with Modal,
i call route laravel in ajax, but why the route is not found .
this is my route in laravel
Route::delete('delete-product/{productId}', 'StoreController#hapus')->name('product.delete');
this is my ajax delete..
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
$('.modal-footer').on('click', '.hapus', function() {
$.ajax({
type: 'DELETE',
url: 'delete-product/' + productId,
data: {
'_token': $('input[name=_token]').val(),
},
when i click icon trash,, modal is show, but in modal when i click delete button then inspect element in browser my route is not found
this is inspect element
Request URL: http://localhost:8000/delete-product/
Request Method: DELETE
Status Code: 404 Not Found
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
why the URL just delete/product .... not include ID ,,
even though my url in ajax called like this
......
url: 'delete-product/' + productId,
.....
this is my blade code
#if(sizeof($resp->content) > 0)
<ul class="the-product">
#foreach($resp->content as $item)
<li>
#if(isset($store) && $store->storeId == $item->store->storeId)
<i class="icofont-ui-love"></i>
#else
<a class="btn btn-danger delete-modal"><i class="fa fa-trash" data-id="{{$item->productId}}"></i></a>
<a class="btn btn-danger" onclick="return myFunction();" href="{{url('edit.product', $item->productId)}}"><i class="icofont-ui-edit"></i></a>
{{-- <i class="icofont-ui-edit"></i> --}}
{{-- <i class="icofont-ui-delete"></i> --}}
#endif
{{-- onclick="ajaxContent(event, this);" --}}
<a href="productDetail/{{ $item->productId }}" class="the-item #if($item->discount > 0)on-promo #endif">
#if($item->discount > 0)
<div class="prod-rib">{{ $item->discount }}% Off</div>
#endif
<img data-src="#if($item->imageId != null){{ config('constant.showImage').$item->imageId }}#else{{ asset('images/no-image-available.png') }}#endif"
src="#if($item->imageId != null){{ config('constant.showImage').$item->imageId }}#else{{ asset('images/no-image-available.png') }}#endif"
alt="{{ $item->productNm }}">
<div class="prod-name">{{ $item->productNm }}</div>
<div class="prod-rev">
#for($i=0; $i<5;$i++)
#if($i<$item->reviewRate)
<img src="{{asset('img/kopi-on.svg')}}" />
#else
<img src="{{asset('img/kopi.svg')}}" />
#endif
#endfor
<span>{{ $item->reviewCount }} ulasan</span>
</div>
<div class="prod-price">
#if($item->discount > 0)
<span>Rp. {{ number_format($item->price,0,',','.') }}</span> Rp. <i>{{ APIHelper::discountPrice($item->discount, $item->price) }}</i>
#else
Rp. <i>{{ APIHelper::discountPrice($item->discount, $item->price) }}</i>
#endif
</div>
</a>
Add to cart <i class="icofont-cart"></i>
{{-- //onclick="ajaxContent(event, this);" --}}
<a href="{{url('/store-detail/'.$item->store->storeId)}}" class="the-store">
<img src="#if($item->store->storePic != null){{ config('constant.showImage').$item->store->storePic }}#else{{ asset('images/no-image-available.png') }}#endif" />
{{ $item->store->storeNm }}
<span>{{ $item->store->percentFeedback }}% ({{ $item->store->totalFeedback }}
feedback)</span>
</a>
</li>
#endforeach
</ul>
<ul class="pagination">
<li class="disabled">
<span><i class="icofont-rounded-double-left"></i></span>
</li><li class="disabled">
<span><i class="icofont-rounded-left"></i></span>
</li>
{{-- active --}}
#for ($i = 0; $i < $resp->totalPages && $i < 5; $i++)
<li class="" onclick="ajaxContent(event, this,null,{'key':'page','value':{{$i+1}} })">
<span>{{$i + 1}}</span>
</li>
#endfor
<li>
<i class="icofont-rounded-right"></i>
</li>
<li>
<i class="icofont-rounded-double-right"></i>
</li>
</ul>
#else
<div class="container clearfix">
<div class="style-msg errormsg mt-5">
<div class="sb-msg"><i class="icon-remove"></i><strong>Maaf</strong>, pencarian anda tidak cocok dengan
produk apapun. Silahkan coba lagi
</div>
</div>
</div>
#endif
<!-- Modal form to delete a form -->
<div id="deleteModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<h3 class="text-center">Are you sure you want to delete the following post?</h3>
<br />
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-2" for="id">ID:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="id_delete" disabled>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-10">
<input type="name" class="form-control" id="title_delete" disabled>
</div>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-danger hapus" data-dismiss="modal">
<span id="" class='glyphicon glyphicon-trash'></span> Delete
</button>
<button type="button" class="btn btn-warning" data-dismiss="modal">
<span class='glyphicon glyphicon-remove'></span> Close
</button>
</div>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
$('.modal-footer').on('click', '.hapus', function() {
$.ajax({
type: 'DELETE',
url: 'delete-product/{productId}',
data: {
'_token': $('input[name=_token]').val(),
},
success: function(data) {
toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
$('.item' + data['id']).remove();
$('.col1').each(function (index) {
$(this).html(index+1);
});
}
});
});
</script>
how to write URL in ajax ?
plis HELP..
In your case, in the following code :
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
ProductId is a local variable having scope function scope. You can not refer it outside unless you declare it globally at the top.
When you try to refer it directly later, it will not be having any value(undefined).
Secondly, You need to change
url: 'delete-product/{productId}'
with
url: '/delete-product/' + productId,
So below is the code :
jQuery(document).ready(function($){
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
});
$('.modal-footer').on('click', '.hapus', function() {
var productId = $('#id_delete').val();
$.ajax({
type: 'DELETE',
url: '/delete-product/' + productId,
data: {
'_token': $('input[name=_token]').val(),
},
success: function(data) {
toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
$('.item' + data['id']).remove();
$('.col1').each(function (index) {
$(this).html(index+1);
});
}
});
});
});

Vue2 trigger render on an independent component over vuex

Inside of a Laravel app I have two independent vue components and I would like to trigger a re-render on the second component.
I use vuex where I already trigger a store mutation and I can see that the data is updated but the component will not re-render.
export default {
store: store,
. //code logic
.
.
methods: {
store: {
//axios async request where on success I trigger store mutation
self.$store.dispatch('getApprovals', 'testing/approvals'); //I can see in console the store request response
}
}
}
than the second component which should re-render
<template>
<div class="portlet light">
<div class="portlet-title tabbable-line">
<div class="caption">
<i class="icon-social-twitter font-dark hide"></i>
<span class="caption-subject bold uppercase">Approvals</span>
</div>
<div class="caption" style="float: right;">
</div>
<ul class="nav nav-tabs">
<li class="active">
Pending
</li>
</li>
</ul>
</div>
<div class="portlet-body">
<div class="tab-content">
<div class="tab-pane active" id="tab_actions_pending">
<div class="mt-actions">
<div class="mt-action" v-for="approval in $store.state.approvals.approvals"
v-show="approval.status === 'pending'">
<div class="mt-action-body">
<div class="mt-action-row">
<div class="mt-action-info ">
<div class="mt-action-icon ">
<i class="icon-magnet"></i>
</div>
<div class="mt-action-details ">
<span class="mt-action-author"
v-show="approval.request_type == 'Timeoff Request'">{{ approval.request_type }} - {{ approval.type }}</span>
<span class="mt-action-author"
v-show="approval.request_type !== 'Timeoff Request'">{{ approval.request_type }} </span>
<p class="mt-action-desc"
v-show="approval.request_type == 'Timeoff Request'">{{
parseFloat(approval.days).toFixed(1) }} day/s requested</p>
<p class="mt-action-desc"
v-show="approval.request_type == 'Timeoff Request'">{{ approval.from}} -
{{ approval.to}}</p>
</div>
</div>
<div class="mt-action-datetime ">
</div>
<div class="mt-action-buttons ">
<span class="label label-warning"> Pending </span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import store from './store';
import {editItem} from './actions';
export default {
vuex: {
getters: {
getApprovals: state => {
return state.approvals
}
}
},
store: store,
created() {
this.$store.dispatch('getApprovals', 'testing/approvals');
},
data() {
return {
approvals: {},
alert: {
show: false,
type: null,
title: null,
message: null,
}
};
}
}
</script>
How do we deal with this cases?

laravel 5.4/ vue js dont iterate my array

Hello I want to make a loop to iterate an array of data retrieve from a controller but I have an error message in vue js I can not find where is my error help me please I start with a vue js
here is my code
controller.php
public function index(){
$post= Posts::with('likes','comments', 'user')->orderBy('created_at','DESC')->get();
return $post ;
}
vue.js
const root = new Vue({
el: '#root',
data: {
msg: 'Update New Post:',
content: '',
posts: []
},
ready: function ready() {
this.created();
},
created: function created() {
var _this = this;
axios.get('http://localhost:8000/mur/posts')
.then(response => {
_this.posts = response.data;
//we are putting data into our posts array
console.log(response.data);
// show if success
Vue.filter('myOwnTime', function(value){
return moment(value).fromNow();
});
})
.catch(function (error) {
console.log(error); // run if we have error
});
}
},
view
<div v-for="post, key in posts">
<div class="col-md-12 col-sm-12 col-xs-12 all_posts">
<div class="col-md-1 pull-left">
<img :src="'{{asset('storage/avatar')}}/' + post.avatar"
style="width:50px;">
</div>
<div class="col-md-10" style="margin-left:10px">
<div class="row">
<div class="col-md-11">
<p><a :href="'{{url('profile')}}/' + post.slug" class="user_name"> #{{post.user.name}}</a> <br>
<span style="color:#AAADB3"> #{{ post.created_at }}
<i class="fa fa-globe"></i></span></p>
</div>
<div class="col-md-1 pull-right">
#if(Auth::check())
<!-- delete button goes here -->
<a href="#" data-toggle="dropdown" aria-haspopup="true">
{{--<img src="{{Config::get('app.url')}}/public/img/settings.png" width="20">--}}
</a>
<div class="dropdown-menu">
<li><a>some action here</a></li>
<li><a>some more action</a></li>
<div class="dropdown-divider"></div>
<li v-if="post.user_id == '{{Auth::user()->id}}'">
<a #click="deletePost(post.id)">
<i class="fa fa-trash"></i> Delete </a>
</li>
</div>
#endif
</div>
</div>
</div>
<p class="col-md-12" style="color:#000; margin-top:15px; font-family:inherit" >
#{{post.content}}
</p>
<div style="padding:10px; border-top:1px solid #ddd" class="col-md-12">
<!-- like button goes here -->
#if(Auth::check())
<div v-for="">
<div v-if="">
<p class="likeBtn" #click="likePost(post.id)">
<i class="fa fa-heart-o"></i>
</p>
</div>
</div>
data : #{{ post.likes.length }}
#endif
</div>
</div>
</div>
web.php
Route::get('mur/posts', 'PostController#index');
posts [ ] return this
[{"id":8,
"user_id":3,
"content":"content 1",
"status":0,
"created_at":"2017-12-27 22:43:20",
"updated_at":"2017-12-27 22:43:20",
"likes":[{"id":2,"posts_id":7,"user_id":3,"created_at":"2017-12-27 16:38:33","updated_at":null}],
"comments":[],
"user":{
"id":3,"name":"toto","sulg":"toto","email":"toto#hotmail.fr","avatar":"215563.jpg","is_actif":"activ\u00e9","created_at":"2017-12-06 15:30:42","updated_at":"2017-12-06 17:04:41"}
},
{"id":7,
"user_id":9,
"content":"coucou",
"status":0,
"created_at":"2017-12-27 16:07:01",
"updated_at":"2017-12-27 16:07:01",
"likes":[{"id":2,"posts_id":7,"user_id":4,"created_at":"2017-12-27 16:38:33","updated_at":null}],
"comments":[],
"user":{"id":9,"name":"blop","sulg":"blop","email":"blop#gmail.com","avatar":"logoBee.png","is_actif":"activ\u00e9","created_at":"2017-12-17 14:37:29","updated_at":"2017-12-17 14:37:29"}}
error in console

Call method other component in vue

How to call method other component in Vue?
I have component HeaderSearch
<template>
<form action="">
<div class="form-group">
<div class="input-group">
<span class="input-group-btn">
<button class="btn" type="button">
<i class="fa fa-search"></i>
</button>
</span>
<input type="text" #keyup="search(keyword)" v-model="keyword" class="form-control" placeholder="Search...">
</div>
</div>
</form>
</template>
<script>
export default {
data(){
return { keyword: "" };
},
methods: {
search: function(keyword){
if(keyword == ''){
// Want call method fetchPost in PostHome component here
}else{
}
}
}
}
</script>
And I have component PostHome
<template>
<div>
<div class="box r_8 box_shadow" v-for="post in posts">
<div class="box_header">
<a :href="post.url">
<h3 class="mg_bottom_10" v-text="post.title"></h3>
</a>
<small v-text="post.description"></small>
<a :href="post.url" class="box_header_readmore">Read more</a>
</div>
<div class="box_body">
<a :href="post.url" v-show="post.thumbnail">
<img :src="post.thumbnail" class="img_responsive" style="min-height: 300px;background-color: #f1f1f1;
">
</a>
</div>
<div class="box_footer" v-show="post.tags.length > 0">
<ul>
<li v-for="tag in post.tags">
<a v-text="tag.name" href="javascript:void(0)"></a>
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
posts: null,
}
},
methods: {
fetchPosts: function(){
var url = base_url + '/user/posts'
this.$http.get(url).then(res => {
this.posts = res.data;
});
}
},
created: function(){
this.fetchPosts();
}
}
</script>
I want when user type keyup to search then if
keyword == ''
call method fetchPost method in PostHome component
You can use Mixins if that method is reusable.
Reference: https://v2.vuejs.org/v2/guide/mixins.html

Resources