Vuejs / laravel image upload receiving empty array - laravel

I have looked at a lot of Q&A on stackoverflow but I can't figure out what I'm doing wrong.
I am building a webshop (to improve my coding), currently working on Add Product bit.
The idea is that I can add a product, which can have multiple 'products'. For example, a T-shirt is one product, but the same t-shirt can be red/green color small/medium size and those have their own stock.
HTML in Vue component
<label class="btn-bs-file btn btn-primary">
Add picture
<input type="file" multiple="multiple" #change="onFileChange($event, index)"/>
</label>
<div v-for="image in form.products[index].files" :key="image.id">
<img :src="image.preview" />
</div>
JS
onFileChange(e, index) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0], index);
},
createImage(file, index) {
var reader = new FileReader();
var vm = this
var formData = new FormData()
formData.append('file', file)
reader.onload = (e) => {
vm.form.products[index].files.push({
file: formData,
preview: e.target.result
});
};
reader.readAsDataURL(file);
},
submit: function() {
let vm = this
this.$api.post('products', this.form,
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
console.log(res.data)
// vm.upload(res.data)
})
.catch(error => {
this.message('error', error, 'Error')
console.log(error)
})
},
PHP
public function store(Request $request)
{
return response()->json($request->all());
}
This is structure (and the response). As you can see, the file is an empty array and I want the actual file here.
{
"name": "Random Name",
"brand": null,
"description": null",
"categories": [],
"note": null,
"products": [
{
"attributes": [],
"color": "random",
"state": "active",
"price": "12",
"files": [
{
"file": [],
"preview": "data:image/png;base64,"
}
]
}
]
}
When I look in my browser (vuejs plugin) it shows me this:
So I guess the formData is in there, but I'm not sure if this is a correct way of doing this and how I would get the formData in the backend.
(I've been at this for over 10 hours, I tried a lot of different things in both backend and frontend, too much to list here..)

Related

Laravel Vue.js after patch request get doesn't load all the data

I want to dynamically hide the "Sign up" button when all the places for the event have been taken. I also update the list of signed-up users.
After clicking on the Signup button the data is saved correctly on the backend but the frontend displays only the pictures of players and there are the usernames. After refreshing the page I can see the usernames and photos. How can I fix my code so all the data will be displayed after the patch?
I'm using 2 Vue components:
AddPlayesComponent
<template>
<div>
<form v-if="freePlaces == true || freePlaces == 1" #submit.prevent="submit()">
<button type="submit" name="participant">Sign up</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
freePlaces: "",
url: "",
}
},
created() {
this.getUrl();
this.fetchStatus();
this.showForm();
},
methods: {
getUrl() {
let id = window.location.href.split('/').pop();
this.url = "/events/" + id + "/team" ;
},
fetchStatus() {
let id = window.location.href.split('/').pop();
axios.get('/events/'+ id + '/availabilty').then((response) => {
this.freePlaces = response.data;
})
},
showForm() {
Echo.channel('team-list-count')
.listen('.players-allowed', (data) => {
this.freePlaces = data.playersAllowed;
})
},
submit() {
axios.post(this.url, {
_method: 'patch'
})
.then(response => {
console.log(response.data);
})
.catch(e => {
console.log("Error is");
console.log(e.data);
});
}
},
computed: {
availabilePlaces() {
return this.freePlaces;
return this.url;
}
}
}
</script>
and TeamListComponent
<template>
<div>
<div v-for="(player, key) in team">
<img :src="'/storage/' + player.profil_photo" alt="profile picture " >
{{ player.username }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
team: [],
}
},
created() {
this.fetchTeam();
this.AddNewPlayerListener();
this.DeleteNewPlayerListener();
},
methods: {
fetchTeam() {
let id = window.location.href.split('/').pop();
axios.get('/events/'+ id + '/team').then((response) => {
this.team = response.data;
})
},
AddNewPlayerListener() {
Echo.channel('team-list')
.listen('.updated-team', (data) => {
this.team = data.team;
})
},
DeleteNewPlayerListener(){
Echo.channel('team-list-delete')
.listen('.updated-team', (data) => {
this.team = data.team;
})
}
},
computed: {
teamList() {
return this.team;
}
}
}
</script>
Controller contains this funcion:
protected function addPlayer($event) {
$registered = $event->registered_participants;
$registered++;
$allowed = $event->allowed_participants;
if($allowed <= $registered) {
$playersAllowed = false;
event(new ParticipantsCounter($playersAllowed));
if($allowed < $registered) {
return redirect()->route('event.show', [ 'event' => $event ]);
}
}
$event->registered_participants = $registered;
$event->save();
$profile = auth()->user()->profile;
$profile->participate()->syncWithoutDetaching([$event->id], false);
$team = $event->participants()->get();
foreach ($team as $player) {
$user = User::where('id', $player->user_id)->first();
$player->username = $user->username;
}
event(new NewParticipant($team));
return redirect()->route('event.show', [ 'event' => $event ]);
}
Data after patch request:
{ "id": 5,
"created_at": "2022-04-12T20:35:03.000000Z",
"updated_at": "2022-04-12T20:35:40.000000Z",
"user_id": 5,
"name": "Marlena",
"familyname": "Test",
"location": "Amblève",
"gender": "x",
"birthdate": "2000-12-12",
"favorite_sport": "hockey",
"biography": "Here comes biography",
"profil_photo": "profiles/kbERb4XrXnu379rtCcyWwb46pOq9UQAtkTKgr42W.jpg" }
Data after refreshing page:
{ "id": 5,
"created_at": "2022-04-12T20:35:03.000000Z",
"updated_at": "2022-04-12T20:35:40.000000Z",
"user_id": 5,
"name": "Marlena",
"familyname": "Test",
"location": "Amblève",
"gender": "x",
"birthdate": "2000-12-12",
"favorite_sport": "hockey",
"biography": "Here comes biography",
"profil_photo": "profiles/kbERb4XrXnu379rtCcyWwb46pOq9UQAtkTKgr42W.jpg",
"username": "testUser",
"pivot": {
"event_id": 1,
"profile_id": 5,
"created_at": "2022-04-25T15:27:37.000000Z",
"updated_at": "2022-04-25T15:27:37.000000Z" }
}
Update:
I solved it by creating an empty array where I push each player after adding a username.
$oldTeam = $event->participants()->get();
$team = [];
foreach ($oldTeam as $player) {
$user = User::where('id', $player->user_id)->first();
$player->username = $user->username;
array_push($team, $player);
}

facebook graph api images GraphRequest

I'm attempting to get the profile image of the user after logging in using FB graph. I'm getting a URL but no image
code:
async fetchProfile(callback) {
return new Promise((resolve, reject) => {
const request = new GraphRequest(
'/me',
{
parameters: { fields: { string: 'picture.width(480),name' } }
},
(error, result) => {
if (result) {
const profile = result
profile.avatar = `https://graph.facebook.com/${result.id}/picture`;
resolve(profile)
} else {
reject(error)
}
}
)
this.requestManager.addRequest(request).start()
})
}
}
response:
{
"avatar": "https://graph.facebook.com/4567877885493457976/picture",
"id": "4567877885493457976",
"name": "Billy Pope",
"picture": {
"data": {
"height": 389,
"is_silhouette": false,
"url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=10219826402184549&width=480&ext=1588823752&hash=AeTZXPsxkrdi79ep",
"width": 480
}
}
}
How do I extract the image from either of these urls - avatar or url? Thanks
To display the image, I changed the view to look like:
{this.state.picture ? (
<Image
source={{ uri: this.state.picture }}
style={styles.imageStyle}
/>
) : null}
adding a condition along with height and width and the image suddenly appeared.

Render HTML of an AJAX response

I'm using Select2 AJAX remote option to fetch data:
$('#t').select2({
ajax: {
url: '../ajax/results.php',
data: function (params) {
return {
search: params.term,
page: params.page || 1
};
}
}
});
So far so good, result are returned like this (please notice the <small> tag):
{
"results": [
{
"id": "1",
"text": "Doe Joe, <small>Mr.</small>"
},
{
"id": "2",
"text": "Smith Anne, <small>Mrs.</small>"
},
{
"id": "3",
"text": "Rossi Mario, <small>Mr.</small>"
},
...
],
"pagination": {
"more": false
}
}
In the <select>, the <small> tag is printed as-is, instead of being parsed.
Select2 docs says that HTML are not rendered by default and that the rendered result must be wrapped in a jQuery object to work, but no further example is given.
All the examples that involve templateResult, indeed, does not give feedback on how to pass AJAX result (i.e. https://select2.org/dropdown#templating )
Please, any help?
The templating example is right, I just need to wrap everything in a <span> tag for it to work:
function formatItem (item) {
if (!item.id) {
return item.text;
}
return $('<span>' + item.text + '</span>');
}
$('#t').select2({
ajax: {
url: '../ajax/results.php',
data: function (params) {
return {
search: params.term,
page: params.page || 1
};
}
},
templateResult: formatItem,
templateSelection: formatItem
});

Show image in datatables codeigniter

sorry for my bad english,
i want to show image in my table using datatables.
var t = $("#mytable").dataTable({
initComplete: function() {
var api = this.api();
$('#mytable_filter input')
.off('.DT')
.on('keyup.DT', function(e) {
if (e.keyCode == 13) {
api.search(this.value).draw();
}
});
},
oLanguage: {
sProcessing: "loading..."
},
processing: true,
serverSide: true,
ajax: {"url": "wisataadmincontroller/json", "type": "POST"},
columns: [
{
"data": "id_wisata",
"orderable": false
},{"data": "nama_wisata"},{"data": "alamat_wisata"},{"data": "no_telp"},{"data": "kategori"},{"data": "longitude"},{"data": "latitude"},{"data": "gambar","render": function(data, type, row) {
return '<img src="'+data+'"style="height:100px;width:100px;" />';
}},{"data": "like"},
{
"data" : "action",
"orderable": false,
"className" : "text-center"
}
],
order: [[0, 'desc']],
rowCallback: function(row, data, iDisplayIndex) {
var info = this.fnPagingInfo();
var page = info.iPage;
var length = info.iLength;
var index = page * length + (iDisplayIndex + 1);
$('td:eq(0)', row).html(index);
}
});
});
and the result :the images are empty
the images are empty because the image source only contains the images file name,
so how to use baseurl in datatables?
Just plug it in?
<img src="<?php echo base_url(); ?>'+data+'"style="height:100px;width:100px;" />

Bootstrap typeahead not showing results

I'm using https://github.com/bassjobsen/Bootstrap-3-Typeahead with Laravel 5.3.
I was using the twitter version before hand which worked fine, except the styles were broken. So I switched to this version but the drop down isn't being rendered. There are no errors either in the console.
If I open the network tab in dev tools, I can see that the request being made and data is being successfully returned. It's just not rendering the suggestion dropdown box.
Anyone know why that could be?
<input type="text" id="search" data-provide="typeahead" autocomplete="off">
var engine = new Bloodhound({
remote: {
url: '/find?q=%QUERY%',
wildcard: '%QUERY%'
},
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
$("#search").typeahead({
hint: true,
highlight: true,
minLength: 0,
source:engine.ttAdapter()
});
Check out my jsfiddle https://jsfiddle.net/yqy995wv/
HTML
<div id="remote">
<input class="typeahead" type="text" placeholder="Oscar winners for Best Picture">
</div>
JS
jQuery(document).ready(function($){
var bestPictures = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'https://twitter.github.io/typeahead.js/data/films/queries/%QUERY.json',
wildcard: '%QUERY'
}
});
$('#remote .typeahead').typeahead(null, {
name: 'best-pictures',
display: 'value',
source: bestPictures
});
});
Your JSON response should be like
[
{
"value": "All Quiet on the Western Front",
},
{
"value": "Gentleman's Agreement",
},
{
"value": "All the Kings Men",
},
{
"value": "All About Eve",
},
{
"value": "An American in Paris",
},
{
"value": "Around the World in 80 Days",
},
{
"value": "The Apartment",
}
]

Resources