I am beginner webdeveloper. I use in my project Laravel 8 and Vue.
I have this code:
<template>
<div class="sm:bg-transparent pt-6 md:mt-16 w-full px-4 md:px-0">
<h1 class="text-dark text-4xl sm:text-3xl font-medium sm:text-center mb-6">{{ __('Archiwum') }}</h1>
<preloader
v-if="isLoadingInProgress"
class="py-8"
:class="preloaderClass"
/>
<div class="text-center" v-if="gasmeters.length == 0 && !isLoadingInProgress">
{{ __('Nie posiadasz jeszcze żadnych odczytów') }}
</div>
<div v-if="gasmeters.length">
<div class="bg-white rounded border border-stroke flex items-start p-6"
v-for="(gasmeter, index) in gasmeters"
v-bind:key="`gasmeter-${index}`">
<div class="mr-6">
<img class="mb-2" :src="gasmeters.img"/> {{ gasmeters }}
</div>
<div class="w-1/5">
<span class="font-bold text-xl text-grey">Lipiec 2020 (#123)</span>
</div>
<div class="w-1/5">
<span class="font-bold text-xl text-grey">Stan:</span> <span>2120</span>
</div>
<div class="w-1/5">
<span class="font-bold text-xl text-grey">Data:</span> <span>2020.01.12</span>
</div>
<div class="w-1/5">
<span class="text-xl">Zgłoszone przez aplikację</span>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import Preloader from "#/common/components/Preloader";
export default {
components: {
Preloader
},
mounted() {
this.loadGasmeters();
},
data() {
return {
gasmeters: [],
isLoadingInProgress: false,
}
},
computed: {
preloaderClass() {
return this.gasmeters.length > 0
? ""
: "loading--transparent loading--block";
}
},
methods: {
loadGasmeters() {
this.isLoadingInProgress = true;
axios
.get(route('api.archive.list'))
.then(response => {
this.gasmeters = _.get(response, "data.data", []);
console.log(this.gasmeters);
})
.catch(error => {
console.log(error);
})
.then(() => {
this.isLoadingInProgress = false;
});
},
}
}
</script>
My php return me:
{
"data": [
[
{
"id": 1,
"value": "99.00",
"settlement_date": "2020-10-20T22:00:00.000000Z",
"loaded_from": "Stan pobrany z systemu BAŁTYKGAZ",
"img": "img/icons/crm.svg",
"created_at": "2020-10-21T15:09:22.000000Z"
},
{
"id": 2,
"value": "109.00",
"settlement_date": "2020-10-20T22:00:00.000000Z",
"loaded_from": "Zgłoszone przez aplikację",
"img": "img/icons/cms.svg",
"created_at": "2020-10-21T17:02:18.000000Z"
}
]
]
}
I have problem with my part this code:
<div v-if="gasmeters.length">
<div class="bg-white rounded border border-stroke flex items-start p-6"
v-for="(gasmeter, index) in gasmeters"
v-bind:key="`gasmeter-${index}`">
<div class="mr-6">
<img class="mb-2" :src="gasmeters.img"/> {{ gasmeters }}
</div>
<div class="w-1/5">
<span class="font-bold text-xl text-grey">Lipiec 2020 (#123)</span>
</div>
<div class="w-1/5">
<span class="font-bold text-xl text-grey">Stan:</span> <span>2120</span>
</div>
<div class="w-1/5">
<span class="font-bold text-xl text-grey">Data:</span> <span>2020.01.12</span>
</div>
<div class="w-1/5">
<span class="text-xl">Zgłoszone przez aplikację</span>
</div>
</div>
</div>
I want replace my img by img from json, "Lipiec 2020 (#123)" => gasmeters.settlement_date (# gasmeters.id), "Stan: " 2120 => Stan: gasmeters.value
How can I make it?
This: {{ gasmeters }} return me:
[ [ { "id": 1, "value": "99.00", "settlement_date": "2020-10-20T22:00:00.000000Z", "loaded_from": "Stan pobrany z systemu BAŁTYKGAZ", "img": "img/icons/crm.svg", "created_at": "2020-10-21T15:09:22.000000Z" }, { "id": 2, "value": "109.00", "settlement_date": "2020-10-20T22:00:00.000000Z", "loaded_from": "Zgłoszone przez aplikację", "img": "img/icons/cms.svg", "created_at": "2020-10-21T17:02:18.000000Z" } ] ]
Please help me
I saw Your problem. Because your response data from service API Laravel is the array in array. If you want to get your right data, you can do in 2 way:
You change the front end data when get from service API, like this:
axios.get(route('api.archive.list'))
.then(response => {
this.gasmeters = _.get(response, "data.data[0]", []);
console.log(this.gasmeters);
})
.catch(error => {
console.log(error);
})
.then(() => {
this.isLoadingInProgress = false;
});
Or you can change the Laravel API like this:
{
"data": [{
"id": 1,
"value": "99.00",
"settlement_date": "2020-10-20T22:00:00.000000Z",
"loaded_from": "Stan pobrany z systemu BAŁTYKGAZ",
"img": "img/icons/crm.svg",
"created_at": "2020-10-21T15:09:22.000000Z"
},
{
"id": 2,
"value": "109.00",
"settlement_date": "2020-10-20T22:00:00.000000Z",
"loaded_from": "Zgłoszone przez aplikację",
"img": "img/icons/cms.svg",
"created_at": "2020-10-21T17:02:18.000000Z"
}
]
}
Related
Can anyone help me? I have created a table with checkbox. but I keep losing the table header name because it was being replaced by the checkbox. The first column with checkbox should be Notify Me and the other is Email Me. How can I put those header names together with the checkbox? here is the code that I have created:
<template>
<Modal #close="doClose">
<template v-slot:container>
<section class="card settings-vue-modal-container">
<header class="card-header">
<h2>Settings</h2>
<!-- <span class="custom-close fa fa-times" #click="doClose"></span> -->
</header>
<div class="card-body">
<div class='table-design'>
<SimpleDatatable
:init_data="tableData"
:init_columns="columns"
:init_is_loading="isTableLoading"
:isColumnCustomizable="false"
:isBoredered="true"
:isTableHeaderSticky="true"
:removeBorderWrapper="true"
:showTotalResult="false"
tableContentClass="users-table-content"
#changePage="changePage"
#getTableData="setTableData"
#getSelectedData="getSelectedData"
>
</SimpleDatatable>
</div>
</div>
<footer class="card-footer">
<div class="btn-group ml-auto float-right">
<button type="button" class="btn btn-secondary btn-close" #click="doClose">Close</button>
</div>
</footer>
</section>
</template>
</Modal>
</template>
<script>
import Modal from "../Reusable/Modal"
import SimpleDatatable from '../Others/SimpleDatatable';
export default {
components: {
Modal,
SimpleDatatable
},
data() {
return {
settingsData: [],
isTableLoading: false,
params: {
page: this.currentPage,
page_limit: 10,
search: '',
role: ''
},
columns: [
{
label: 'Task Schedule',
field: 'name',
align: 'center',
default: true
},
{
label: 'Notify Me',
type: 'checkbox',
align: 'center',
width: 200
},
{
label: 'Email Me',
type: 'checkbox',
align: 'center',
width: 200
}
],
tableData: {},
currentPage: 1,
selectedData: [],
requiredData: {},
errors: {},
name: '',
};
},
created() {
this.getTableData()
},
watch: {
currentPage(newValue, oldValue) {
this.params.page = newValue
this.getTableData()
}
},
methods: {
doClose() {
this.errors = {};
this.name = '';
this.$emit('close');
},
changePage(event) {
this.currentPage = event
},
setTableData(data) {
this.tableData = data
},
getSelectedData(data) {
this.selectedData = data.map(x => x.id)
},
getTableData() {
this.isTableLoading = true
let url = '/tasks/api/getAll'
axios
.post(url, this.params)
.then(response => {
this.setTableData(response.data)
this.isTableLoading = false
})
.catch(errors => {
this.isTableLoading = false
console.log(errors)
})
},
}
}
</script>
Thank you. Below is also the SimpleDatatable being used:
<template>
<div class="row">
<SeeMore
:content="this.seeMoreContent"
v-show="seeMoreModalVisibility"
#close="seeMoreModalVisibility=false"
/>
<div class="col-lg-12">
<CustomizeColumnModal
v-show="showColumnModal"
#close="showColumnModal = false"
:columns="init_columns"
#getCols="getColumn"
/>
</div>
<div class="col-lg-12">
<div
class="panel panel-default"
style="margin-bottom: 0"
:class="{ 'no-border': removeBorderWrapper }"
>
<div
class="panel-body"
style="margin-bottom: 0"
:class="{ 'no-border': removeBorderWrapper }"
>
<loading :active.sync="isLoading" :is-full-page="fullPage" style="z-index: 3;"></loading>
<div class="pull-left">
<slot name="functional_upper_left"></slot>
<b
class="ml-3"
v-if="data.total && showTotalResult && totalResultPosition === 'upperLeft' "
>Total Result: {{data.total | addComma }}</b>
</div>
<button
class="btn btn-lg btn-primary pull-right"
v-if="isColumnCustomizable"
#click="showColumnModal = true"
style="margin-bottom: 15px;"
>
<span class="fa fa-list" style=" margin-right: 5px;"></span> Columns
</button>
<slot name="functional_buttons"></slot>
<div class="table table-responsive" style="overflow: auto; max-height: 550px;">
<table
class="table table-hover table-striped"
:class="{ 'table-bordered': isBoredered }"
style="margin-bottom: 0"
>
<thead>
<tr>
<th
v-for="(col, index) in columns"
:class="{'amzentrix-th-sticky' : isTableHeaderSticky, 'with-select-dropdown': col.type === 'checkbox' && isSelectOptions }"
:key="index"
:style="{ minWidth: (col.width) ? `${col.width}px`: '100px', textAlign: (col.align) ? `${col.align}` : 'left' }"
>
<template v-if="col.type === 'checkbox'">
<div class="dropdown">
<input type="checkbox" #click="doSelectAll" v-model="isSelectAll" />
<a
class="dropdown-toggle"
id="dropdownSelectOptions"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
v-if="isSelectOptions"
/>
<div class="dropdown-menu" aria-labelledby="dropdownSelectOptions">
<span class="dropdown-item" #click="doSelectAllOnly">Select All</span>
<span class="dropdown-item" #click="doSelectTop(10)">Select Top 10</span>
<span class="dropdown-item" #click="doSelectTop(20)">Select Top 20</span>
</div>
</div>
</template>
<template v-else-if="col.sortable">
<div class="sortable_col" #click="sortCol(index)">
<span>{{ col.label }}</span>
<span class="sortable_icons">
<i class="fa fa-sort-up" :class="{ active: col.currentSort === 'ASC'}" />
<i
class="fa fa-sort-down"
:class="{ active: col.currentSort === 'DESC'}"
/>
</span>
</div>
</template>
<template v-else>{{ col.label }}</template>
</th>
</tr>
</thead>
<tbody v-if="data.total !== 0">
<template v-for="(row, index) in data.data">
<tr :key="index">
<td
v-for="(col, index) in columns"
:class="tableContentClass"
:style="{
textAlign: (col.align) ? `${col.align}` : 'left',
'vertical-align': (col.valign) ? col.valign : 'middle'
}"
:key="index"
>
<template v-if="col.type == 'checkbox' ">
<div class="vue-checkbox">
<input
type="checkbox"
:checked="row.selected"
#click="doSelect(row, $event)"
/>
</div>
</template>
<template v-else-if="col.type === 'action'">
<slot :name="`action-${row.id}`">
<slot name="action" :data="row" />
</slot>
</template>
<template v-else-if="col.type == 'date'">{{ timeHumanize(row[col.field]) }}</template>
<template
v-else-if="col.type == 'complete_date'"
>{{ completeDateFormat(row[col.field]) }}</template>
<template v-else-if="col.type == 'raw'">
<div v-html="row[col.field]"></div>
</template>
<template v-else-if="col.type == 'rounded_numbers'">
<div>{{ row[col.field] ? Number(row[col.field]).toFixed(4) : row[col.field] }}</div>
</template>
<template
v-else-if="col.type == 'status'"
>{{ row[col.field] ? 'Active': 'Inactive' }}</template>
<template v-else-if="col.type == 'more'">
<div v-if="row[col.field]">
<p v-html="seeMoreTexts(row[col.field].replace(/<\/?[^>]+(>|$)/g, ''))"></p>
<small
class="see-more"
#click="seeMore(row[col.field])"
v-if="row[col.field].length> 20"
>See More</small>
</div>
<p v-else>-</p>
<!-- {{ row[col.field] ? '<h1>awit</h1>' : '-' }} -->
</template>
<template v-else-if="col.type == 'field_value'">
<slot name="field_value" :data="row"></slot>
</template>
<template v-else>{{ row[col.field] ? row[col.field] : '-' }}</template>
</td>
</tr>
</template>
</tbody>
<tbody v-else>
<tr>
<td align="center" colspan="1000">
<slot name="no-result">
<span style="margin-right: 5px">No Data Found.</span>
</slot>
</td>
</tr>
</tbody>
</table>
</div>
<!-- PAGINATION -->
<nav v-if="data.total && data.total !== 0 && !data.single">
<ul class="pagination" :class="`float-${paginationPosition}`">
<li
class="page-item pagination-total-result px-3"
v-if="data.total && showTotalResult && totalResultPosition === 'bottomPaginationLeftSide'"
>
Total Result:
<b class="ml-2">{{data.total | addComma }}</b>
</li>
<slot name="pagination-left" />
<li class="page-item pr-3 page-limit-select" v-if="isCustomResultPerPage">
<label for="results-per-page">Results per page:</label>
<input
class="form-control"
id="results-per-page"
type="number"
min="1"
#change="handleChangeItemsPerPage"
v-model="page_limit"
/>
</li>
<li
class="page-item"
:class=" data.current_page <= 1 ? 'disabled' : '' "
#click=" changePage((data.current_page - 1))"
>
<a
class="page-link"
:href=" (data.current_page > 1) ? `#page-${data.current_page - 1}` : `#page-1`"
aria-label="Previous"
>
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li>
<li
class="page-item"
v-for="(n, index) in pagination(data.current_page, data.last_page)"
:class="(n === data.current_page) ? 'active' : ''"
:key="index"
#click="changePage(n)"
>
<a class="page-link" :href="(typeof n == 'number') ? `#page-${n}` : '#' ">{{ n }}</a>
</li>
<li
class="page-item"
:class=" data.current_page >= data.last_page ? 'disabled' : '' "
#click=" changePage((data.current_page + 1))"
>
<a
class="page-link"
:href=" (data.current_page < data.last_page) ? `#page-${data.current_page + 1}` : `#page-${data.last_page}`"
aria-label="Next"
>
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li>
<slot name="pagination-right" />
</ul>
</nav>
</div>
</div>
</div>
</div>
</template>
<style scoped src='bootstrap/dist/css/bootstrap.min.css'></style>
<script>
import moment from "moment";
import CustomizeColumnModal from "./Datatable/CustomizeColumn";
import SeeMore from "./SimpleDatatableModal";
export default {
components: {
CustomizeColumnModal,
SeeMore
},
props: {
init_data: {
type: Object,
required: true
},
init_columns: {
type: Array,
required: true
},
init_is_loading: {
type: Boolean,
default: false
},
init_page_limit: {
type: Number,
default: 0
},
isSelectOptions: {
type: Boolean,
default: false
},
isColumnCustomizable: {
type: Boolean,
default: false
},
isBoredered: {
type: Boolean,
default: false
},
isTableHeaderSticky: {
type: Boolean,
default: false
},
isCustomResultPerPage: {
type: Boolean,
default: false
},
removeBorderWrapper: {
type: Boolean,
default: false
},
showTotalResult: {
type: Boolean,
default: false
},
totalResultPosition: {
type: String,
default: "upperLeft"
},
tableContentClass: {
type: String,
default: ""
},
paginationPosition: {
type: String,
default: "left"
}
},
data() {
return {
data: { total: 0 },
columns: this.init_columns,
isLoading: this.init_is_loading,
fullPage: false,
isSelectAll: false,
showColumnModal: false,
seeMoreContent: "",
seeMoreModalVisibility: false,
page_limit: this.init_page_limit
};
},
watch: {
init_data(newData, oldData) {
this.data = newData;
this.isSelectAll = false;
if (this.isSelectOptions) {
this.getSelectedData();
}
},
init_is_loading(newData, oldData) {
this.isLoading = newData;
if (this.isSelectOptions) {
this.checkSelectHeaderModel(); //Will reset isSelectAll State. Important if you're using checkbox and with dynamic data.
}
},
init_columns(newCols) {
this.columns = newCols;
},
init_page_limit(newData) {
this.page_limit = newData;
}
},
filters: {
addComma(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
},
methods: {
resetSortColFields() {
const withSortColFields = this.columns.filter(col => col.currentSort);
const resetColFields = withSortColFields.map(col => {
col.currentSort = null;
return col;
});
},
//returns an object with sortType (eg. ASC or DESC ) and field (eg. DATE, ID)
sortCol(index) {
const { currentSort } = this.columns[index];
let sort = null;
this.resetSortColFields();
switch (currentSort) {
case "ASC":
sort = null;
break;
case "DESC":
sort = "ASC";
break;
default:
sort = "DESC";
}
this.columns[index].currentSort = sort;
this.$emit("sort", {
sortType: sort,
field: sort ? this.columns[index].field : null
});
},
doSelectAll(event) {
//single property for single set of data, means no paginated data.
//usually you want to use this if you're not using primarily the api of laravel's pagination.
//you just need to pass an initial object data with data and single properties
if (!this.data.total && !this.data.single) {
event.preventDefault();
return;
}
this.isSelectAll = !this.isSelectAll;
this.data.data.forEach(element => {
element.selected = this.isSelectAll;
});
if (!this.isSelectAll) this.$emit("getDeselectedData", this.data.data);
this.$emit("getTableData", this.data);
this.getSelectedData();
},
doSelectAllOnly() {
if (!this.isSelectAll) this.doSelectAll();
},
doSelectTop(num) {
this.data.data.forEach((element, index) => {
if (num > index) element.selected = true;
});
this.getSelectedData();
},
checkSelectHeaderModel() {
// to check if all data from the data is selected, if true, checkbox from header must be checked.
if (!this.data.data) return;
const newDataLength = this.data.data.length;
const newSelectedDataLength = this.data.data.filter(data => data.selected)
.length;
this.isSelectAll =
newDataLength && newDataLength === newSelectedDataLength ? true : false;
},
doSelect(row, event) {
let checked = Boolean(row.selected);
row.selected = !checked;
if (!row.selected) {
this.$emit("getDeselectedItem", row);
}
this.getSelectedData();
},
getSelectedData() {
const selected = this.data.data.filter(el => el.selected);
this.checkSelectHeaderModel();
this.$emit("getSelectedData", selected);
},
getColumn(event) {
if (this.isColumnCustomizable) {
this.columns = event;
this.$emit("getSelectedColumns", event);
}
},
timeHumanize(date) {
return moment(date).isValid() ? moment(date).fromNow() : date;
},
completeDateFormat(date) {
return moment(date).isValid()
? moment(date).format("MMM Do YYYY h:mm:ss a")
: date;
},
changePage(pageNumber) {
this.handleChangeItemsPerPage();
if (
pageNumber > 0 &&
pageNumber <= this.data.last_page &&
typeof pageNumber == "number" &&
this.data.current_page != pageNumber
)
this.$emit("changePage", pageNumber);
},
pagination(c, m) {
let current = c,
last = m,
delta = 3,
left = current - delta,
right = current + delta + 1,
range = [],
rangeWithDots = [],
l;
for (let i = 1; i <= last; i++) {
if (i == 1 || i == last || (i >= left && i < right)) {
range.push(i);
}
}
for (let i of range) {
if (l) {
if (i - l === 2) {
rangeWithDots.push(l + 1);
} else if (i - l !== 1) {
rangeWithDots.push("...");
}
}
rangeWithDots.push(i);
l = i;
}
return rangeWithDots;
},
seeMoreTexts(text) {
return text.length > 20 ? text.substring(0, 40) + "..." : text;
},
seeMore(data) {
this.seeMoreContent = data;
this.seeMoreModalVisibility = true;
},
handleChangeItemsPerPage(event) {
let value;
let changePage = false;
if (typeof event == "object") {
value = parseInt(event.target.value);
changePage = true;
} else {
value = parseInt(this.page_limit);
}
if (value <= 0 || typeof value != "number" || !value) {
value = 10;
this.page_limit = 10;
}
this.$emit("handleChangeItemsPerPage", parseInt(value), changePage);
}
},
mounted() {
//single property for single set of data, means no paginated data.
//usually you want to use this if you're not using primarily the api of laravel's pagination.
//you just need to pass an initial object data with data and single properties
this.data =
this.init_data.total || this.init_data.single
? this.init_data
: { total: 0 };
}
};
</script>
I have a page called Home.vue i have a router link which is id once users click it it takes them to the page, how can i display the data elements of the clicked id?
<li class="ta-track-card column col-2 flex-column" v-for="faq in faqs">
<div class="inner">
<div class="artwork" role="link">
<router-link :to="`/album/${faq.id}`"><span :style="`background-image: url('http://localhost/mymusic/${faq.artworkPath}');`"></span></router-link>
</div>
<div class="info">
<div class="title white-primary-hover"><router-link :to="`/album/${faq.id}`">{{ faq.title }}</router-link></div>
<div class="username light-white-hover">
<span>by </span>
<router-link :to="`/artist/${faq.artistId}`">{{ faq.artist }}</router-link>
</div>
<div class='released'>Released On {{ faq.albumdate }}</div>
</div>
</div>
</li>
Below is the Album.vue Page where i display the data
<div class="entityInfo">
<div class="leftSection" v-for="faq in faqs">
<img :src="/""faq.artworkPath">
</div>
<div class="rightSection" v-for="faq in faqs" :key="faq.id">
<h2 class="_good">{{ faq.title }}</h2>
<p class="_me">By {{ faq.artist }}</p>
<p class="_me">1 songs</p>
<p class="_me">{{ faq.albumdate }}</p>
</div>
Below is Script i use:
<script>
import axios from 'axios';
export default {
name: 'album',
data: () =>({
faqs: [],
songs: [],
errors: []
}),
created() {
axios.get('http://localhost/mymusic/rest/api/album/read')
.then(response => {
this.faqs = response.data.data;
})
.catch(e => {
console.log(e),
this.errors.push(e)
})
}
}
</script>
Below is the Sample API:
{
"data": [
{
"id": "41",
"artistId": "38",
"title": "Red Handed",
"artist": "Peruzzi & Mayorkun",
"artworkPath": "assets/images/artwork/red.jpg",
"albumdate": "2018-09-24"
},
{
"id": "40",
"artistId": "37",
"title": "FEFE (feat. Nicki Minaj & Murda Beatz)",
"artist": "6ix9ine",
"artworkPath": "assets/images/artwork/fefe.jpg",
"albumdate": "2018-07-22"
},
}
Please how can i display the element of the Id i click from the router
As i can see you are passing the id in the route you can retrieve it using id = this.$route.params.id and store it in a temporary variable.And in created just retrieve the data by passing id in post parameter and changing your query accordingly.Or the other option is to loop over through your retrieved data and filter them from the selected id.
Or rather then filter create the data object as id->value pairs to directly access them through id and you will have to make single api call.
I'd like to pass a SQL query to a Javascript function, found in my view, which will populate a HTML table using the DataTables API. I'm having trouble converting the object array into plain JSON. How would I go about doing so?
[web.php]
Route::get('/admin', function () {
$users = DB::connection('mysql')->select('SELECT * FROM users');
return view('admin', compact('users'));
});
[admin.blade.php] (HTML)
<div class="row">
<div class="col-lg-6">
<div class="card mb-3">
<div class="card-header"><i class="fa fa-user"></i> Users</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-striped table-compact" width="100%" id="userTable" cellspacing="0"></table>
</div>
</div>
</div>
</div>
</div>
[admin.blade.php] (Javascript)
<script type="text/javascript">
$(document).ready(function() {
$('#userTable').DataTable( {
"scrollX": true,
"scrollY": '55vh',
"scrollCollapse": true,
"paging": false,
dom: 'ft',
"aaData": "{{ $users }}",
"aoColumns": [
{ "sTitle": "Name", "mData": "name" },
{ "sTitle": "Email", "mData": "email" },
]
} );
} );
</script>
[Example JSON object/array returned from database]
array:1 [
0 => {#195
+"id": 1
+"name": "Josh_W"
+"email": "user#email.com"
+"group": "Admin"
+"level": 5
+"password": "PASSWORD"
+"remember_token": null
+"created_at": "2017-10-12 14:42:38"
+"updated_at": "2017-10-12 14:42:38"
}
]
The select() method returns an array. You need to collect() the array and then call toJson():
<script type="text/javascript">
$(document).ready(function() {
$('#userTable').DataTable( {
"scrollX": true,
"scrollY": '55vh',
"scrollCollapse": true,
"paging": false,
dom: 'ft',
"aaData": {!! collect($users)->toJson() !!},
"aoColumns": [
{ "sTitle": "Name", "mData": "name" },
{ "sTitle": "Email", "mData": "email" },
]
} );
} );
</script>
To avoid escaping your JSON use the {!! !!} syntax.
See the Laravel documentation on collections and displaying data on views for reference.
I want to put Description's button in php file like this:
But when I tried to make code like this,
<?php
use miloschuman\highcharts\HighchartsAsset;
use yii\helpers\Html;
HighchartsAsset::register($this)->withScripts(['modules/exporting', 'modules/drilldown']);
$this->title = 'Highcharts Test';
?>
<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('Description', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="x_panel">
<div id="my-chart" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<!-- jenis kelamin magister -->
<?php $this->registerJs("
$(function () {
$('#my-chart').highcharts({
title: {
text: 'Jumlah Pelamar Magister Berdasarkan Jenis Kelamin'
},
xAxis: {
categories: $tahundaftarpelamar
},
yAxis: {
title: {
text: 'Jumlah'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
credits:
{
enabled: false
},
series: [{
name: 'Laki-Laki',
data: $lakilakipelamar
}, {
name: 'Perempuan',
data: $perempuanpelamar
},
{
name: 'Tidak Diketahui',
data: $tidakdiketahuipelamar
}]
});
});
")?>
</div>
</div>
<!-- usia -->
<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('Description', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="x_panel">
<div id="my-chart2" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<?php $this->registerJs("
$(function () {
$('#my-chart2').highcharts({
title: {
text: 'Jumlah Pelamar Magister Berdasarkan Usia'
},
xAxis: {
categories: $tahundaftarusiapelamar
},
yAxis: {
title: {
text: 'Jumlah'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
credits:
{
enabled: false
},
series: [{
name: '<25',
data: $usialess25pelamar
}, {
name: '25-29',
data: $usiabetw25pelamar
},
{
name: '30-34',
data: $usiabetw30pelamar
},
{
name: '35-39',
data: $usiabetw35pelamar
},
{
name: '40-44',
data: $usiabetw40pelamar
},
{
name: '45-49',
data: $usiabetw45pelamar
},
{
name: '>=50',
data: $usiamore50pelamar
},
{
name: 'Tidak Lengkap',
data: $usianotcompletepelamar
}
]
});
});
")?>
</div>
</div>
the result was like this:
What may I do so that I can get the result like the first picture? Thank you in advance
I get stuck on a foreach loop inside my blade template after hours of trial and failure I need some help.
My Controller
public function menue() {
$restaurants = User::with('articles')->get();;
return view('pages.menues')->withRestaurants($restaurants);
}
My foreach
#foreach($restaurants as $restaurant)
<div class="panel panel-default">
<div class="panel-heading">
#foreach($restaurant->articles as $article)
{{$article->title}}
<span class="float-right">{{$article->published_at}}</span>
#endforeach
</div>
<div class="panel-body">
#foreach($restaurant->articles as $article)
{{$article->body}}
#endforeach
{{$restaurant->name}}
</div>
</div>
#endforeach
This is what I'm trying to loop trough:
{
"id":1,
"name":"Sam",
"email":"sam#me.com",
"created_at":"2016-07-26 15:03:51",
"updated_at":"2016-07-27 15:39:55",
"articles":[
{
"id":1,
"user_id":1,
"title":"Monday Afternoon",
"body":"got it",
"created_at":"2016-07-27 15:31:05",
"published_at":"2016-07-27 15:30:00",
"excerpt":null,
"updated_at":"2016-07-27 15:31:05"
},
{
"id":3,
"user_id":1,
"title":"Good Morning Wednesday",
"body":"lorem ipsum",
"created_at":"2016-07-27 11:38:37",
"published_at":"2016-07-27 11:38:00",
"excerpt":null,
"updated_at":"2016-07-27 11:38:37"
},
{
"id":4,
"user_id":1,
"title":"Good Morning Thursday",
"body":"lorem ipsum ",
"created_at":"2016-07-27 11:39:14",
"published_at":"2016-07-28 14:38:00",
"excerpt":null,
"updated_at":"2016-07-27 11:39:14"
},
{
"id":5,
"user_id":1,
"title":"Wednesday Afternoon",
"body":"Hallo Welt",
"created_at":"2016-07-27 14:55:00",
"published_at":"2016-07-27 14:54:00",
"excerpt":null,
"updated_at":"2016-07-27 14:55:00"
}
]
}
Output of my blade template
The result is instead of four posts I get only 2 posts. Each of them contains to other posts. How can I display all 4 posts individually in my view?
Try This
#foreach($restaurants as $restaurant)
#foreach($restaurant->articles as $article)
<div class="panel panel-default">
<div class="panel-heading">
{{$article->title}}
<span class="float-right">{{$article->published_at}}</span>
</div>
<div class="panel-body">{{$article->body}}</div>
</div>
#endforeach
#endforeach