Change format date using javascript from timestamp php [duplicate] - laravel

This question already has answers here:
How to get current formatted date dd/mm/yyyy in Javascript and append it to an input [duplicate]
(7 answers)
Closed 4 years ago.
can javascript change the date format taken from php like this: 2018-09-22 05:20:48 to like this Saturday,22 September ? iam using vue.js and laravel. because this date is taken from the database using a query i dont know how to get int time and it will be passing to vue component.
Vue Component :
<tr v-for="(category,index) in allCategories">
<td class="v-align-middle"> <img :src="category.images[0].link" class="img-fluid categoriesImg" alt=""> </td>
<td class="v-align-middle">{{category.category}}</td>
<td class="v-align-middle">{{formatDate(category.created_at)}}</td>
</tr>
<script>
import {mapGetters} from 'vuex';
export default {
name:"category",
computed: {
...mapGetters({
allCategories:'allCategories'
}),
},
created(){
// this.$swal('Hello Vue world!!!');
this.$store.dispatch('GetAllCategories');
},
methods:{
formatDate(date){
let tanggal = new Date(date);
return tanggal;
},
}
}
</script>
Result
"2018-09-21T22:20:48.000Z"

momentjs is the best soltion.
Make sure you set the right format (https://momentjs.com/docs/#/parsing/string-format/)
formatDate(date){
let tanggal = moment(date, 'YYYY-MM-DD HH:mm:ss').format('dddd,DD MMMM');
return tanggal;
},

You can use below code :
var monthNames = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var dayNames=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
d = new Date(date);
time = dayNames[d.getDay()] + ", " + d.getDate() + monthNames[d.getMonth()] ;
For more information you can checkout the Date in javaScript

Related

Filter with date range while using HTML Builder - yajra Datatables

I used the Yajra Laravel Datatables and HTML Builder plugin for displaying my data, now I want to add two date input fields which are start date and end date that can be used to get the data within a range of time, so I can download the data according to date range. Please how can I go about this?
/**
* Show the application.
* More info DataTables : https://yajrabox.com/docs/laravel-datatables/master
*
* #param Datatables $datatables
* #return \Illuminate\Http\Response
* #throws \Exception
*/
public function index(Datatables $datatables)
{
$columns = [
'name',
'id_card',
'date',
];
if ($datatables->getRequest()->ajax()) {
return $datatables->of(Attendance::all())
->addColumn('name', function(Attendance $user) {
return User::where('id', $user->user_id)->first()->name;
})
->toJson();
}
$html = $datatables->getHtmlBuilder()
->columns($columns)
->parameters([
'responsive' => true,
'autoWidth' => false,
'dom' => 'Bfrtip',
'buttons' => ['csv', 'excel', 'pdf', 'print'],
]);
return view('backend.attendances.index', compact('html'));
}
Blade
<div class="card-body">
<p id="date_filter" class="form-inline">
<span id="date-label-from" class="date-label"><b>From:</b> </span><input class="date_range_filter date form-control input-sm" type="text" id="min" />
<span id="date-label-to" class="date-label"><b>To:</b></span> <input class="date_range_filter date form-control input-sm" type="text" id="max" />
</p>
<div class="table-responsive">
{!! $html->table(['class' => 'table table-hover']) !!}
</div>
</div>
........
........
{!! $html->scripts() !!}
I use
PHP Version : 7.2
Laravel Version: 6
Laravel-DataTables Version: 9.0
You can pass extra parameters in yajra datatable as service from frontend.
window.LaravelDataTables["dataTableBuilder"] = $("#dataTableBuilder").on('preXhr.dt', function (e, settings, data) {
data.startDate= 2020-10-27 0:00:00;
data.endDate = 2020-10-30 23:59:59;
}).DataTable({
"serverSide": true,
"processing": true,
"ajax": {
url: "{{route('route.index')}}",
type: "GET"
}
});
LaravelDataTables.dataTableBuilder.ajax.reload()
I hope It will be helpful for who use yajra datatable as service :)
If you view page source of your page this {!! $html->scripts() !!} generate this code
window.LaravelDataTables["dataTableBuilder"] = $("#dataTableBuilder").DataTable
so DataTables instance store as global variable. This means any JS code will have access to this variable. in order to send a request with parameter you can do like this.
<script>
(function () {
const doSubmit = () => {
LaravelDataTables.dataTableBuilder.ajax.url({
type: 'POST',
data: function (d) {
d.start = document.getElementById('start').value
d.end = document.getElementById('end').value
}
})
LaravelDataTables.dataTableBuilder.ajax.reload()
}
const send = document.getElementById('send')
send.addEventListener('click', doSubmit)
})()
</script>

How show server's error in vee-validate with different name?

In my vue/cli 4/vuex / bootstrap-vue project / "vue-router": "^3.1.3" /
"vee-validate": "^3.2.1" / "vue-resource": "^1.5.1",project I use backend rest for saving data and
I have a problem that getting errors from server like
{"message":"The given data was invalid.","errors":{"title":["The title has already been taken."]}}
I can not show it on my form as that is big form with many elements and modal form has more
complicated name , not “title” and I suppose that is why server's error is not shown:
<b-modal id="saveCurrentFilterModal" scrollable size="lg" style="min-width: 720px !important;">
<ValidationObserver
ref="saveCurrentFilterModalForm"
v-slot="{handleSubmit}"
>
<form ref="form" #submit.stop.prevent="handleSubmitOnSaveCurrentFilterOptionsSubmit">
<b-form-group
:state="nameState"
label="Name"
label-for="name-input"
invalid-feedback="Name is required"
>
<ValidationProvider
name="save_current_filter_title" // MORE COMPLICATED TITLE NAMW!
rules="required|max:100"
v-slot="{ errors }"
>
<b-form-input
id="save_current_filter_title"
v-model="save_current_filter_title"
placeholder="Edit saved filter title"
autocomplete="off"
></b-form-input>
<p class="validation_error">{{ clearErrorMessage(errors[0]) }}</p>
</ValidationProvider>
</b-form-group>
<b-button type="submit" size="sm" variant="outline-secondary" class="ml-4">
<i :class="'action_link '+getHeaderIcon('save')"></i>Save
</b-button>
</form>
</ValidationObserver>
handleSubmitOnSaveCurrentFilterOptionsSubmit() {
this.$refs.saveCurrentFilterModalForm.validate().then(success => {
console.log('handleSubmitOnSaveCurrentFilterOptionsSu success::')
console.log(success)
if (!success) {
return;
}
let filters = {
...
}
let self = this
self.$http.post(self.apiUrl + '/personal/ad-saved-filters', filters).then(({data}) => {
console.log(data)
self.showPopupMessage("Saved filter", 'Saved filter was successfully saved !', 'success');
self.$bvModal.hide('saveCurrentFilterModal')
}, error => {
console.error(error)
self.$refs.saveCurrentFilterModalForm.setErrors(error.body.errors); // TO GET ERRORS FROM
self.showPopupMessage("Saved filter", error.body.message, 'warn');
});
});
}, // handleSubmitOnSaveCurrentFilterOptionsSubmit(evt) {
Is there is a way to fix it ?
When you call setErrors you have to have the correct field names specified. So if the server returns title but you need save_current_filter_title, you'll have to have some sort of object that keeps track of the relationship between the server's field names and the client's. For instance, on the client side, you could have this:
let filters = {
...
}
let self = this
self.$http.post(self.apiUrl + '/personal/ad-saved-filters', filters).then(({data}) => {
...
}, error => {
//define this in data, but for example:
var sKey2cKey = {
title: 'save_current_filter_title',
name: 'complicated-client-name',
//etc
}, convertedErrors = {};
Object.keys(error.body.errors).forEach((key) => {
convertedErrors[sKey2cKey[key]] = error.body.errors[key];
});
self.$refs.saveCurrentFilterModalForm.setErrors(convertedErrors);
self.showPopupMessage("Saved filter", error.body.message, 'warn');
});

How to add an image to an event on Vue FullCalendar? imageurl returns undefined

I'm trying to add dynamically an image to the FullCalendar events with Vue. But first of all, I'm testing with a static data and the image doesn't show up.
This is what I'm trying to do after several research:
<template>
...
<FullCalendar
defaultView="timeGridWeek"
header="null"
:slotDuration="slotDuration"
:plugins="calendarPlugins"
#dateClick="handleDateClick"
:allDaySlot="false"
:columnHeaderFormat='columnHeaderFormat'
:hiddenDays="hiddenDays"
:themeSystem="themeSystem"
:minTime="minTime"
:maxTime="maxTime"
:contentHeight="contentHeight"
:events="tutor_applications_not_scheduled"
:config="config"
#eventRender="eventRender"
/>
...
</template>
<script>
import moment from 'moment'
import FullCalendar from '#fullcalendar/vue'
import dayGridPlugin from '#fullcalendar/daygrid'
import timeGridPlugin from '#fullcalendar/timegrid'
import interactionPlugin from '#fullcalendar/interaction'
import bootstrapPlugin from '#fullcalendar/bootstrap'
export default {
components: {
FullCalendar
},
data(){
return {
tutor_application_setup_id: this.$route.params.tutor_application_setup_id,
loading: false,
uri: '/tutor-applications-schedules/',
calendarPlugins: [dayGridPlugin, timeGridPlugin, interactionPlugin, bootstrapPlugin],
slotDuration: '01:00',
columnHeaderFormat: {weekday:'long'},
hiddenDays: [], //[0,6] - Sunday and Saturday
themeSystem: 'bootstrap',
minTime: '10:00', // will be dynamic
maxTime: '17:00', // will be dynamic
contentHeight: 'auto',
config: {
timeFormat: 'h(:mm) a',
eventClick: function(event) {
if (event.url) {
location.replace(event.url);
return false;
}
}
},
tutor_applications_schedules: [],
tutor_applications_not_scheduled: [],
tutor_applications_scheduled: [],
errors: [],
}
},
methods: {
handleDateClick(arg){
alert(arg.date)
},
loadTutorApplicationsSchedules(){
axios.get(this.uri + this.tutor_application_setup_id).then(response=>{
this.tutor_applications_schedules = response.data.tutor_applications_schedules
this.loadTutorApplicationsNotScheduled()
this.loading = true
});
},
loadTutorApplicationsNotScheduled(){
// this.tutor_applications_schedules.forEach(schedule => {
// if(!schedule.is_scheduled){
this.tutor_applications_not_scheduled.push({
title: 'TEST TITLE',
start: '2019-05-22 10:00',
end: '2019-05-22 13:00',
imageurl: '/images/profile/1557196883.png'
});
// }
// });
},
eventRender: function(event, eventElement) {
console.log(event) // returning everything
console.log(event.imageurl) // returning undefined
if (event.imageurl) {
eventElement.find("div.fc-content").prepend("<img src='" + event.imageurl +"' width='16' height='16'>");
}
},
loadTutorApplicationsScheduled(){
},
moment: function (date) {
return moment(date)
},
},
mounted(){
this.loadTutorApplicationsSchedules()
}
}
</script>
The result returns only the time and the title in the correct date.
I also tried to insert the img tag to the title attribute, and changed the eventRender, like below:
...
title: '<img src="/images/profile/1557196883.png" />TEST TITLE',
...
eventRender: function(event, element, view) {
var title = element.find( '.fc-title' );
title.html(title.text());
},
It's returning the html tag as string, like <img src="/images/profile/1557196883.png" />TEST TITLE.
Some of my dependencies are:
"vue": "^2.5.17",
"#fullcalendar/bootstrap": "^4.1.0",
"#fullcalendar/core": "^4.1.0",
"#fullcalendar/daygrid": "^4.1.0",
"#fullcalendar/interaction": "^4.1.0",
"#fullcalendar/timegrid": "^4.1.0",
"#fullcalendar/vue": "^4.1.1",
"babel-runtime": "^6.26.0",
"vue-full-calendar": "^2.7.0",
I don't know which approach to follow anymore. Any help? Thank you.
UPDATE
I realized that some params has changed (Full Calendar Updates) and I changed my eventRender function, and now I can read the imageurl. However, I'm stuck how in Vue to find a tag and prepend with my image tag.
My code now is like this:
eventRender: function(info) {
console.log(info) // returning everything
console.log(info.event.extendedProps.imageurl) // returning the image path correctly
if (info.event.extendedProps.imageurl) {
info.el.find("div.fc-content").prepend("<img src='" + info.event.extendedProps.imageurl +"' width='16' height='16'>"); // this line is the problem now
}
},
It's returning the error [Vue warn]: Error in v-on handler: "TypeError: info.el.find is not a function", and I don't know how to fix it.
For whom it may concern :), this thread helped me, and I figured out what to do. I changed my eventRender to this:
eventRender: function(info) {
if (info.event.extendedProps.imageurl) {
info.el.firstChild.innerHTML = info.el.firstChild.innerHTML + "<img src='" + info.event.extendedProps.imageurl +"' width='40' height='40'>";
}
},
In this case, I can be even more flexible like:
info.el.firstChild.innerHTML = "<div><h4><a href='#'>"+ info.event.title +"</a></h4><img src='" + info.event.extendedProps.imageurl +"' width='40' height='40'></div>";
etc.
I hope this can help someone else!
Define a variable in data as imageURL: "",
Define img tag in html where you want to show it as
<img v-if="imageURL!=''" :src="imageURL" width='16' height='16'>
Your renderer function
eventRender: function(info) {
if (info.event.extendedProps.imageurl) {
this.imageURL = info.event.extendedProps.imageurl;
}
}
This is how I did mind by putting this function into methods
eventRender(info) {
info.el.firstChild.innerHTML = `
<a class="rounded-lg fc-day-grid-event fc-h-event fc-event f-start fc-end">
<div class="h-12">
<span class="fc-title text-white flex ml-3">
<img class="img-circle avatar-small h-8 w-8 p-1" src="${info.event.extendedProps.imageurl}">
<span class="ml-3 self-center font bold">${info.event.extendedProps.username}</span>
</span>
</div>
</a>
`
},
Now to change color dynamically for each event I did it from Laravel Resource
'backgroundColor' => $this->status === 1 ? '#48BB78' : '#F6E05E'
Tried to use :class inside the eventRender and didn't work.
So you can just send in the API the color you want based on a condition instead and perform the operation on laravel.

Laravel and vuejs -> how to pass Controller data into my Vue view?

I am discovering php, laravel, vuejs at the same time and I guess there are some things I didn't get well yet ;)
I made a new component "tableau" which is a basic table and would like to use it at many places in my app, where I would just specify its title, columns and data.
FootballerController is the place where I get all my data.
Here is what is working now:
app.js
const tableau = new Vue({
components:{tableau:Tableau
},
data: function() {
return {
title: "the best footballers",
searchQuery: '',
gridColumns: ['footballer', 'cote', 'nationalite'],
gridData: [
{ footballer: 'Remond', cote: 951, nationalite:'USA' },
{ footballer: 'Marcel', cote: 935, nationalite:'ESP' },
{ footballer: 'Stian', cote: 923, nationalite:'NOR' },
{ footballer: 'Martin', cote: 923, nationalite:'USA' },
{ footballer: 'Pierre', cote: 918, nationalite:'ESP' },
]
}
}
}).$mount('#tableau');
footballer.blade.php
<tableau
v-bind:titre="title"
:rows="gridData"
:columns="gridColumns "
:filter-key="searchQuery" >
</tableau>
TableauComponent
<template>
<div >
<h1 >{{titre}}</h1>
<table >
<thead>
<tr>
<th v-for="key in columns"
{{ key | capitalize }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="entry in rows">
<td v-for="key in columns">
{{entry[key]}}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name:'tableau',
props: {
rows: Array,
columns: Array,
titre: String
}
}
</script>
This works.
Then, here is what I would like: being able to put my values from the controller into footballer.blade.php, which is using TableauComponent.vue
FootballerController
public function footballer($id){
//process to get all this data in DB ($footballer, $gridData, $gridColumns, $title)
$footballer= (Footballer::select(SOME REQUEST)->where('id', '=', $id)->get())[0];
return view('footballers/footballer', ['footballer' => $footballer,
'gridData' => $gridData,
'gridColumns' => $gridColumns,
'title' => $title] );
}
And in footballer.blade.php
<tableau
v-bind:titre="{{ $title }}"
:rows="{{ $gridData }}"
:columns="{{ $gridColumns }}" >
</tableau>
Then in app.js I wouldn't need data anymore
const tableau = new Vue({
components:{tableau:Tableau
}
}).$mount('#tableau');
But this doesn't work and tells me "Property or method is not defined on the instance but referenced during render"
I don't manage at all and am worndering is I have the good way of doing: Should I not get my data in FootballerController? If not, where can I get it then?
Thanks a lot in advance.
When you use {{ value }} in both Blade & javascript framework at the same time. You need to use #{{ value }} to avoid collision between Blade & Vue.
try
<tableau
v-bind:titre="#{{ $title }}"
:rows="#{{ $gridData }}"
:columns="#{{ $gridColumns }}" >
</tableau>
Besides that, when you use :rows="value", the value must be javascript syntax, otherwise when rows="value", the value would be treated as string.
You might need to use json_encode to format your data from the Laravel, or use #json if you're using Laravel 5.5^.
Your are using ':' symbol before your attributes in your blade, which means 'v-bind' as the doc says : VueJS Shorthands.
So first, for assigning a String to a props, you don't need ':' before 'titre'.
Then, to solve your problem you could try to add a default value to your props, for example :
props: {
rows: {
default: []
},
columns: {
default: []
},
titre: {
default: ''
}
}
I didn't try but I think it should works.
Thanks a lot, indeed the php array to javascript array was the issue.
In the php controller, I parse my data into json
'gridData' =>json_encode($gridData),
In the php view footballer.blade.php
<tableau
titre="{{ $title }}"
rows="{{ $gridData }}">
</tableau>
And in my Vue view, I was getting an array, and changed the code for this:
rows: {
type: String,
default: ""
}
var rowsArray = JSON.parse(this.rows)
Now it seems like the data I get after my request isn't properly parsed, but that's another point :)

push value in select option in vue

I m new to Vue and don't know how to solve this kind of problem I search a lot but haven't find any solution related to my problem
here is my code
<tbody >
<tr v-for="(col, index) in cols">
<td>12345</td>
<td><select class="form-control" v-model="col.select1" >
<option>Select Shop</option>
<option v-for="option1 in options1" :value="option1.name">
{{option1.name}}</option>
</select>
</td>
</tbody>
<script>
export default {
data(){
return{
cols: [],
options1:[]
}
},
methods:{
getshop(){
var _this=this
return this.$http.get('http://localhost:3000/api/companyproducts') .then(function (response) {
return response.data;
})
},
onClick(){
this.cols.push({
this.options1:this.getshop(), //how i can push getshop return value to select option
qty:0 });
},
},
}
</script>
suppose if my table has 3 value then 3 row getting created along with 3 select option in ShopIdFrom column as show in image now the problem is that when i m try to push the value getting from getshop function into select option. i.e ShopIdFrom select option i does not have any option value .i.e this.cols.push not working for dynamically select option. what i m doing wrong or is there any other way to achieve this
try this hope it will help you
onClick(){
var t;
var _this=this
this.getshop().then(function(value) {
_this.options1= value
});
this.cols.push({
select1:'',
qty:0 });
},

Resources