I'm making an online exam and I want to paginate the questions in different pages but the problem is that when I go to the next page the previous answers gone because the page refresh so how can I make the Laravel pagination withou refresh?
running Laravel 5.8
controller code:
$questions = $exam->questions()->paginate(1);
return view('exam.exam',compact('questions','exam'));
$questions = $exam->questions()->paginate(1);
return view('exam.exam',compact('questions','exam'));
view code
{!! $questions->render() !!}
This, sadly, can't be achieved without a little bit of asynchronous javascript - unless you want to preload all pages.
Your best bet is creating an API that returns paginated entries in a json format, then load it with javascript.
finally i did it using vue.js and axios
app.js code :
data: {
posts: {},
pagination: {
'current_page': 1
}
},
methods: {
fetchPosts() {
axios.get('posts?page=' + this.pagination.current_page)
.then(response => {
this.posts = response.data.data.data;
this.pagination = response.data.pagination;
})
.catch(error => {
console.log(error.response.data);
});
}
},
mounted() {
this.fetchPosts();
}
//and i added the pagination in a Component:
<template>
<nav class="pagination is-centered" role="navigation" aria-label="pagination">
<a class="pagination-previous" #click.prevent="changePage(1)" :disabled="pagination.current_page <= 1">First page</a>
<a class="pagination-previous" #click.prevent="changePage(pagination.current_page - 1)" :disabled="pagination.current_page <= 1">Previous</a>
<a class="pagination-next" #click.prevent="changePage(pagination.current_page + 1)" :disabled="pagination.current_page >= pagination.last_page">Next page</a>
<a class="pagination-next" #click.prevent="changePage(pagination.last_page)" :disabled="pagination.current_page >= pagination.last_page">Last page</a>
<ul class="pagination" style="display:block">
<li v-for="page in pages">
<a class="pagination-link" :class="isCurrentPage(page) ? 'is-current' : ''" #click.prevent="changePage(page)">{{ page }}</a>
</li>
</ul>
</nav>
</template>
<style>
.pagination {
margin-top: 40px;
}
</style>
<script>
export default {
props: ['pagination', 'offset'],
methods: {
isCurrentPage(page) {
return this.pagination.current_page === page;
},
changePage(page) {
if (page > this.pagination.last_page) {
page = this.pagination.last_page;
}
this.pagination.current_page = page;
this.$emit('paginate');
}
},
computed: {
pages() {
let pages = [];
let from = this.pagination.current_page - Math.floor(this.offset / 2);
if (from < 1) {
from = 1;
}
let to = from + this.offset - 1;
if (to > this.pagination.last_page) {
to = this.pagination.last_page;
}
while (from <= to) {
pages.push(from);
from++;
}
return pages;
}
}
}
</script>
<!-- begin snippet: js hide: false console: true babel: false -->
and make a route to get the pagination infromation into:
NOTE: this route will be used to return the pagination data into json only
Route::get('/posts', 'postContoller#pagination');
and in controller make a function to return the pagination information:
public function pagination(\App\post $post){
$posts = $post->paginate(1);
$response = [
'pagination' => [
'total' => $posts->total(),
'per_page' => $posts->perPage(),
'current_page' => $posts->currentPage(),
'last_page' => $posts->lastPage(),
'from' => $posts->firstItem(),
'to' => $posts->lastItem()
],
'data' => $posts
];
return response()->json($response);
}
now create a new view and paste this into
<div id="app">
<div v-for="post in posts">
<div class="font-weight-bold p-4"> #{{post.qname}}</div>
</div>
</div>
and create a route for it
Route::get('/', 'postController#index');
Related
I develop an ecommerce application in nuxtjs frontend and laravel backend.But it is difficult to upload image and save it in the database.Can anyone help me solve the problem ?
Here example of Nuxt Or Vuejs image uploader with Laravel API. I left a comment inside the code for you.
First of all, you must make upload.vue component with this content.
<template>
<div class="container">
<label class="custom-file" for="file">
{{files.length ? `(${files.length}) files are selected` : "Choose files"}}
<input #change="handleSelectedFiles" id="file" multiple name="file" ref="fileInput" type="file">
</label>
<!--Show Selected Files-->
<div class="large-12 medium-12 small-12 cell">
<div class="file-listing" v-for="(file, key) in files">{{ file.name }} <span class="remove-file" v-on:click="removeFile( key )">Remove</span></div>
</div>
<!--Submit Button && Progress Bar-->
<div>
<button #click="upload">Start Upload</button>
- Upload progress : {{this.progress}}
</div>
</div>
</template>
<script>
export default {
data() {
return {
files : [],
progress: 0
}
},
computed: {
/*The FormData : Here We Make A Form With Images Data To Submit.*/
form() {
let form = new FormData();
this.files.forEach((file, index) => {
form.append('files[' + index + ']', file);
});
return form;
}
},
methods : {
handleSelectedFiles() {
let selectedFiles = this.$refs.fileInput.files;
for (let i = 0; i < selectedFiles.length; i++) {
/*Check Already Has Been Selected Or Not ...*/
let isFileExists = this.files.find(file => file.type === selectedFiles[i].type && file.name === selectedFiles[i].name && file.size === selectedFiles[i].size && file.lastModified === selectedFiles[i].lastModified);
if (!isFileExists)
this.files.push(selectedFiles[i]);
}
},
removeFile(key) {
this.files.splice(key, 1);
},
upload() {
const config = {
onUploadProgress: (progressEvent) => this.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
};
this.$axios.post('host-url/upload-image', this.form, config)
.then(res => {
this.progress = 0;
this.files = [];
console.log(res)
})
.catch(err => console.log(err))
}
}
}
</script>
<style>
.custom-file {
padding: 1.2rem;
border-radius: .8rem;
display: inline-block;
border: 2px dashed #a0a0a0;
}
.custom-file input {
display: none;
}
</style>
After this, we must make an endpoint in Laravel API routes like this:
Route::post('/upload-image', 'UploadController#image');
In the last, Put this codes on upload
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function image(Request $request)
{
$request->validate([
'files' => ['required', 'array'],
'files.*' => ['required', 'image','min:5','max:5000']
]);
$uploadedFiles = [];
foreach ($request->file('files') as $file) {
$fileName = bcrypt(microtime()) . "." . $file->getClientOriginalExtension();
$file->move('/uploads', $fileName);
array_push($uploadedFiles, "/uploads/{$fileName}");
}
return response($uploadedFiles);
}
}
Attention: Progress in localhost is so fast, then if you want to test it in local upload a file largest than 50 MB.
I'm using Vuejs and Laravel building a live feed app, but i found that it is difficult to get associate data from collection in Vuejs, is there anyway to get those data easily?
Here is my attempt:
<div class="sl-item" v-for="post, index in posts">
<a href="javascript:void(0)">
<div class="sl-content">
{{post}}
<br>
------------------------
<br>
{{getUser(post.user_id)}}
</div>
</a>
</div>
Here is my methods that i intend to retrieve user record:
methods: {
getUser (id)
{
return axios.get("/user/getUser/" + id)
.then(response => {
console.log(response.data);
return response.data;
});
}
},
But this is what i got:
I can log what i get in console, but i can't display or access the thing i return from my method.
Is there any other easier way to achieve this?
You fetching all the data from collection. that's why you also getting unwanted data in your object
in your current situation (without changing in your controller script) you can access those data as like:
public function index(Request $request)
{
if ($request->ajax()) {
return Post::with(['user' => function($query){
$query->select(['id', 'name'])
}])
->select(['id', 'title', 'description'])
->get;
}
}
if you do this in your controller, then in your vue file,
data:function(){
return{
posts: [],
};
},
methods: {
getPosts ()
{
return axios.get("/posts")
.then(response => {
this.posts = response.data;
});
}
},
and in component:
<div class="sl-item" v-for="post, index in posts">
<a href="javascript:void(0)">
<div class="sl-content">
{{post.title}}
<br>
------------------------
<br>
{{ post.user.name }}
</div>
</a>
</div>
I'm trying to show user projects list where user_id column is match with auth()->user()->id.
the problem i have is how to define what function of my resourced route to use.
Code
Controller
class ProjectController extends Controller
{
public function index()
{
$projects = Project::orderby('id', 'desc')->latest()->take(10)->get();
return response()->json($projects);
}
public function userprojects()
{
$projects = Project::orderby('id', 'desc')->where('user_id', '=', Auth::user()->id)->get();
return $projects;
}
}
Api route
Route::resource('projects', 'Api\ProjectController', ['except' => ['create', 'edit', 'destroy']]);
Vue component
<template>
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Your Published Projects <span class="badge badge-info">{{projects.length}}</span></div>
<div class="card-body">
<ul>
<li v-for="project in projects" :key="project.id">
{{project.title}} - {{project.user_id}}
</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
projects: []
}
},
created(){
this.fetchProjects();
},
methods:{
fetchProjects(){
var self = this;
axios.get('api/projects')
.then(function (resp) {
self.projects = resp.data;
})
.catch(function (resp) {
console.log(resp);
alert("Could not load projects");
});
},
},
}
</script>
Question
How do I tell my component to not load index function but to load
data from userprojects function?
So you could add a new route
Route::get('projects-user', 'Api\ProjectController#userprojects')->name('userprojects');
In js.
axios.get(Router('userprojects').url()).then(response => {
this.userprojects= response.data;
});
Also you could do just this in the controller
class ProjectController extends Controller
{
public function index()
{
if(Auth::check()){
$projects = Project::orderby('id', 'desc')->where('user_id', '=', Auth::user()->id)->get();
}else{
$projects = Project::orderby('id', 'desc')->latest()->take(10)->get();
}
return response()->json($projects);
}
}
You can create a new route before the resource route and use it:
Route::get('projects/me', 'Api\ProjectController#userprojects', ['except' => ['create', 'edit', 'destroy']]);
Route::resource('projects', 'Api\ProjectController', ['except' => ['create', 'edit', 'destroy']]);
then on your component:
axios.get('api/projects/me')
.then(function (resp) {
self.projects = resp.data;
})
I have passed this collection (postFavourite) to my vue component via props.
[{"id":1,"user_id":1,"post_id":2,"created_at":"2018-07-24 09:11:52","updated_at":"2018-07-24 09:11:52"}]
How do I then check if any instance of user_id in the collection is equal to userId which is the current logged in user (also sent via props).
Tried
let pf = _.find(this.postFavourite, { "user_id": this.userId})
Keep getting undefined as the value of the pf variable even though this.userID is equal to 1.
New to JS and Vue.js so any help would be great.
Here is the vue component code.
<template>
<div>
<i v-show="this.toggle" #click="onClick" style="color: red" class="fas fa-heart"></i>
<i v-show="!(this.toggle)" #click="onClick" style="color: white" class="fas fa-heart"></i>
</div>
</template>
<script>
export default {
data() {
return {
toggle: 0,
}
},
props: ['postData', 'postFavourite', 'userId'],
mounted() {
console.log("Post is :"+ this.postData)
console.log("User id is: "+ this.userId)
console.log("Favourite Object is :" +this.postFavourite);
console.log(this.postFavourite.find(pf => pf.user_id == this.userId));
},
methods: {
onClick() {
console.log(this.postData);
this.toggle = this.toggle ? 0 : 1;
}
}
}
</script>
This is how I passed the props to vue
<div id="app">
<favorite :post-data="'{{ $post->id }}'" :post-favourite="'{{Auth::user()->favourite }}'" :user-id="'{{ $post->user->id }}'"></favorite>
</div>
I gave up on lodash and find and just messed around with the data in the chrome console to work out how to check the value I wanted.
Then I built a loop to check for the value.
If it found it toggle the like heart on of not leave it off.
This will not be the best way to solve this problem but I'm just pleased I got my first real vue component working.
<template>
<div>
<i v-show="this.toggle" #click="onClick" style="color: red" class="fas fa-heart"></i>
<i v-show="!(this.toggle)" #click="onClick" style="color: white" class="fas fa-heart"></i>
</div>
</template>
<script>
export default {
props: ['postData', 'postFavourite', 'userId']
,
data() {
return {
toggle: 0,
favs: [],
id: 0
}
},
mounted () {
var x
for(x=0; x < this.postFavourite.length; x++){
this.favs = this.postFavourite[x];
if(this.favs['post_id'] == this.postData) {
this.toggle = 1
this.id = this.favs['id']
}
}
},
methods: {
onClick() {
console.log(this.postData)
if(this.toggle == 1){
axios.post('favourite/delete', {
postid: this.id
})
.then(response => {})
.catch(e => {
this.errors.push(e)
})
}
else if(this.toggle == 0){
axios.post('favourite', {
user: this.userId,
post: this.postData
})
.then(response => {
this.id = response.data
})
.catch(e => {
this.errors.push(e)
})
}
this.toggle = this.toggle ? 0 : 1;
}
}
}
</script>
Where I pass my props.
<favorite :post-data="'{{ $post->id }}'"
:post-favourite="{{ Auth::user()->favourite }}"
:user-id="'{{ Auth::user()->id }}'"></favorite>
Thanks to all that tried to help me.
From just the code you provided, I see no issue. However lodash is not required for this problem.
Using ES2015 arrow functions
let pf = this.postFavourite.find(item => item.user_id === this.userId);
Will find the correct item in your array
You can read more about this function in the mdn webdocs
You can use find() directly on this.postFavourite like this:
this.postFavourite.find(pf => pf.user_id == this.userId);
Here is another way to do it that might help you as well.
[EDIT]
In order to use find() the variable needs to be an array, this.postFavourite is sent as a string if you didn't use v-bind to pass the prop thats what caused the error.
To pass an array or an object to the component you have to use v-bind to tell Vue that it is a JavaScript expression rather than a string. More informations in the documentation
<custom-component v-bind:post-favourite="[...array]"></custom-component>
I've got a form that I want to send by ajax-post to my controller. Meanwhile the HTML is waiting for the generation and saving of the records, I want to display the progress (for now just numbers). I really don't understand why the following code doesn't update <div id="progress"> with Session::get('progress').
Controller:
public function postGenerate() {
// getting values from form (like $record_num)
Session::flash('progress', 0);
$i = 1;
for ($i; $i < $record_num; $i++) {
$record = new Record();
// adding attributes...
$record->save;
Session::flash('progress', $i);
}
$response = Response::make();
$response->header('Content-Type', 'application/json');
return $response;
}
Javascript:
#section('scripts')
<script type="text/javascript">
$(document).ready(function() {
$('#form-overview').on('submit', function() {
setInterval(function(){
$('#progress').html( "{{ Session::get('progress') }}" );
}, 1000);
$.post(
$(this).prop('action'),
{"_token": $(this).find('input[name=_token]').val()},
function() {
window.location.href = 'success';
},
'json'
);
return false;
});
});
</script>
#stop
HTML:
#section('content')
{{ Form::open(array('url' => 'code/generate', 'class' => 'form-inline', 'role' => 'form', 'id' => 'form-overview' )) }}
<!-- different inputs ... -->
{{ Form::submit('Codes generieren', array('class' => 'btn btn-lg btn-success')) }}
{{ Form::close() }}
<div id="progress">-1</div>
#stop
Well, that's because {{ Session::get('progess') }} is only evaluated once, when the page is first rendered. The only way to do what you want is to actually make extra AJAX requests to a different URL that reports the progress. Something like this:
Controller
// Mapped to yoursite.com/progress
public function getProgess() {
return Response::json(array(Session::get('progress')));
}
public function postGenerate() {
// getting values from form (like $record_num)
Session::put('progress', 0);
Session::save(); // Remember to call save()
for ($i = 1; $i < $record_num; $i++) {
$record = new Record();
// adding attributes...
$record->save();
Session::put('progress', $i);
Session::save(); // Remember to call save()
}
$response = Response::make();
$response->header('Content-Type', 'application/json');
return $response;
}
JavaScript
#section('scripts')
<script type="text/javascript">
$(document).ready(function() {
$('#form-overview').on('submit', function() {
setInterval(function(){
$.getJSON('/progress', function(data) {
$('#progress').html(data[0]);
});
}, 1000);
$.post(
$(this).prop('action'),
{"_token": $(this).find('input[name=_token]').val()},
function() {
window.location.href = 'success';
},
'json'
);
return false;
});
});
</script>
#stop