How to save session() value " " in laravel? - laravel

In app.js -> methods i have this.chat.image.push(''); and in axios.post send i have
methods:{
send(){
if(this.message.length != 0)
{
this.chat.message.push(this.message);
this.chat.user.push('');
this.chat.image.push('');
this.chat.time.push('');
axios.post('admin/send', {
message : this.message,
chat:this.chat
})
.then(response => {
// console.log(response);
this.message = '';
})
}
},
getOldMessages(){
axios.post('admin/getOldMessage')
.then(response => {
if (response.data != '') {
this.chat = response.data;
}
})
},
And in mounted() i have
mounted(){
this.getOldMessages();
Echo.channel('chat')
.listen('ChatEvent', (e) => {
this.chat.message.push(e.message);
this.chat.user.push(e.user);
this.chat.image.push('source/admin/assets/images/avatar/'+e.image);
axios.post('admin/saveToSession',{
chat : this.chat
.then(response => {
console.log(response);
})
})
})
}
In Controller i have function saveToSession
public function saveToSession(request $request)
{
session()->put('chat',$request->chat);
}
In send() function i get image=" "; but when I save to the session it returns null, How come it returns to the value = " " ? Thanks

Check that value in $request->chat are coming properly or not if yes then you can try other methods as well
Via a request instance
$request->session()->put('key', 'value');
Via the global helper
session(['key' => 'value']);

Related

Download an image to React Native from a Laravel server?

I am looking to download an image stored on a server into my React Native app.
I had a function that looked like this:
public function image(Request $request, $id)
{
$company = Company::find($id);
$filePath = storage_path() . '/app/' . $company->image;
return response()->file($filePath);
}
And it returned nothing I could read within the app when I tried the following function:
setCompany = async () => {
let company = await AsyncStorage.getItem('currentCompany');
company = JSON.parse(company);
if (company.image !== null) {
let image = await getCompanyPicture({company_id: company.id});
console.log('Here: ', image);
// This is blank, react native returns a warning about data not being of a readable type
}
this.setState({company});
};
I am able to get the image in base_64 using this method:
public function image(Request $request, $id)
{
$company = Company::find($id);
$file_path = storage_path('/app/' . $company->image);
if (file_exists($file_path)) {
$fileData = file_get_contents($file_path);
$fileEncode = base64_encode($fileData);
return response()->json(['status' => 'success', 'data' => ['file' => $fileEncode, 'file_path' => $file_path]]);
}
return response()->json(['status' => 'failure', 'data' => ['file' => null, 'file_path' => $file_path]]);
}
Here is my Axios method too just in case:
export const sendRequest = async (url, data, token, method) => {
let headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Method': 'POST, GET, DELETE, PUT',
};
if (typeof token !== 'undefined' && token !== 'undefined' && token.length) {
headers.Authorization = 'Bearer ' + token;
}
if (method === 'get' && data) {
url +=
'?' +
Object.keys(data)
.map((value) => {
return value + '=' + data[value];
})
.join('&');
data = null;
}
return await axios({
headers: headers,
method: method ? method : 'post',
url: url,
data: data,
})
.then((response) => {
return response;
})
.then((json) => {
return json.data;
})
.catch((error) => {
console.error(error);
if (
error.message !== 'Network Error' &&
error.response.status !== 500 &&
error.response.status !== 413
) {
return error.response.data;
} else if (error.message === 'Network Error') {
return {
status: 'error',
message: 'Unable to connect to server',
};
} else if (error.response.status === 500) {
return {
status: 'error',
message: 'Internal Server Error',
};
} else if (error.response.status === 413) {
return {
status: 'error',
message: 'The file(s) size is too large',
};
} else {
return {
status: 'error',
message: error.message,
};
}
});
};
If anyone could comment on the performance impact of using base_64 instead of the straight file download that would also be helpful
But ultimately I would like a solution for handling the Laravel response()->file() if possible (which I'll use if base_64 is less efficient)
I'm not sure about RN code syntax, but I've ready code with jQuery+poorJS, which looks like this:
$.ajax({
url: "load-image-url", // URL FOR GET REQUEST
cache:false,
xhr: function() { // ACTUALLY THIS PART CAN BE USED AND CUSTOMIZED BY YOU
let xhr = new XMLHttpRequest();
xhr.responseType= 'blob'
return xhr;
},
success: function(data) {
let url = window.URL || window.webkitURL;
$('#image').attr('src', url.createObjectURL(data));
},
error: function(err) {
// console.log(err);
}
}).fail(function() {
$('#ss_product_image').attr('src', "default-image-url.jpg");
});
In my example I've used GET request (but you can try to modify it and test if you want, honestly IDK about that).
This is the back-end part:
public function image(Request $request, $id)
{
// HERE YOU NEED TO GET YOUR IMAGE (using $id or/and $request params) CONTENT FROM SOMEWHERE YOU WANT
$content = <CONTENT>;
return response()->make($content, 200, [
'Content-Type' => (new \finfo(FILEINFO_MIME))->buffer($content),
'Content-length' => strlen($content),
]);
}
I was able to solve this issue by using rn-blob-fetch.
The files are downloaded into a temp cache which can then be accessed for previewing and saving.
this is my function now:
downloadFiles = async (isReply) => {
let {enquiry, reply} = this.state;
this.setState({isLoading: true});
const token = await AsyncStorage.getItem('userToken');
let filePaths = [];
let fileCount = 0;
let files = enquiry.files;
if (isReply) {
files = reply.files;
}
const dirToSave =
Platform.OS == 'ios'
? RNFetchBlob.fs.dirs.DocumentDir
: RNFetchBlob.fs.dirs.DownloadDir;
new Promise((resolve, reject) => {
for (var i = 0; i < files.length; i++) {
var id = files[i].file_id;
var name = files[i].file.file_name;
var ext = extension(name);
const configOptions = Platform.select({
ios: {
appendExt: ext,
fileCache: true,
title: name,
path: `${dirToSave}/${name}`,
},
android: {
useDownloadManager: true,
notification: true,
mediaScannable: true,
fileCache: true,
title: name,
path: `${dirToSave}/${name}`,
},
});
var mime = content(ext);
let headers = {
'Content-Type': mime,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Method': 'POST, GET, DELETE, PUT',
Authorization: 'Bearer ' + token,
};
RNFetchBlob.config(configOptions)
.fetch('GET', BASE_API + '/enquiries/files/download/' + id, headers)
.then(async (response) => {
RNFetchBlob.fs.writeFile(
configOptions.path,
response.data,
'base64',
);
filePaths.push({
title: configOptions.title,
path: configOptions.path,
ext: extension(configOptions.title),
mime,
});
fileCount++;
if (fileCount >= files.length) {
resolve('Download Successful!');
}
})
.catch((error) => {
console.log('File Download Error: ', error.message);
reject('Download Failed');
});
}
})
.then((data) => {
this.setState({isLoading: false, filePaths});
})
.catch((error) => {
console.log('Download Promise Error: ', error);
this.setState({isLoading: false});
});
};
previewDocument = (id) => {
let {filePaths} = this.state;
if (Platform.OS == 'ios') {
RNFetchBlob.ios.openDocument(filePaths[id].path);
} else if (Platform.OS == 'android') {
RNFetchBlob.android.actionViewIntent(
filePaths[id].path,
filePaths[id].mime,
);
}
};

Why axios does't catch errors from server response?

i'm using laravel and vue, i use axios to make a request, that request response a json, but if cannot find the data, return a 404,but catch of axios don't work
this is the front code
methods: {
updateData: function () {
axios.post('acd/' + this.number + '/' + this.date)
.then((response) => {
this.setData(response['data'])
}).catch(err => {
console.log("this dont display")
});
setTimeout(this.updateData, 1000)
this.updateDoughnutChart();
this.updateLineChart();
this.updatePieChart();
},
and this is the back code
public function getAcd(Request $request, $id, $date)
{
$dateClient = new Carbon($date);
$dateServer = new Carbon;
if($dateClient->format('Y-m-d') == $dateServer->format('Y-m-d'))
{
$data = App::make('vodia')->getAcd($id);
}
else
{
$data = Call::where('acd', $id)->whereDate('created_at', $date)->firstOrFail();
$data = json_decode($data->data);
}
return response()->json(($data));
}
this is the console error
Uncaught (in promise) Error: Request failed with status code 404
Think the syntax for the catch block is not correct
your code
axios.post('acd/' + this.number + '/' + this.date)
.then((response) => {
this.setData(response['data'])
}).catch(err => {
console.log("this dont display")
});
suppose to be
axios.post('acd/' + this.number + '/' + this.date)
.then((response) => {
this.setData(response['data'])
}).catch((err) => {
console.log(err)
});

Laravel vue axios post no data is returned as json response

I created a simple system for commenting posts or videos. Everything works fine.
A function called loadComments() shows comments related to posts or videos.
When a user submits a new comment, the comment is created, but in order to view the new comment I have to refresh the page because I receive an undefined response.
Here the store function in the controller
public function store(Request $request)
{
$comments = Comment::create([
'comment' => $request->comment,
'user_id' => auth()->user()->id,
'post_id' => $request->post_id
]);
return response()->json([
'comments' => $comments,
'success' => 'Comment created successfully!'
],200);
}
Here the addComment method:
addNewComment() {
const formData = {
comment: this.comment,
post_id: this.propsVideoid
}
axios
.post(this.commentsUri, formData)
.then(response => {
this.comments.unshift(response.data.comments)
})
.catch(error => {
this.errors = [];
if(error.response.status == 422) {
this.errors = error.response.data.errors;
}
})
},
Here the load and add methods together
addNewComment() {
const formData = {
comment: this.comment,
post_id: this.propsVideoid
}
axios
.post(this.commentsUri, formData)
.then(response => {
this.comments.unshift(response.data.comments)
})
.catch(error => {
this.errors = [];
if(error.response.status == 422) {
this.errors = error.response.data.errors;
}
})
},
loadComments() {
axios.get(this.commentsListUri, {
params: {
post_id: this.propsVideoid
}
}).then(response => {
this.comments = response.data.comments;
});
},
},
mounted() {
this.loadComments();
}
The addNewComment() method inserts the new comment in the database, but it does not return any json response.

this2.$dispatch is not a function

I'm trying to use the dispatch function in vue.js like this.
But I'm getting an error saying this2.$dispatch is not a function...like you can see on the screenshot
message.vue
export default {
data(){
return{
message:'',
isLoading:false,
}
},
methods:{
addMessage(){
if(this.message !=''){
this.sendData();
} else{
this.$fire({
title: "Error",
text: "Enter some text.",
type: "error",
timer: 3000
}).then(r => {
console.log(r.value);
});
setTimeout(() => {
this.isLoading = false
},700)
}
},
sendData(){
this.isLoading = true;
this.$http.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms}).then((response) => {
console.log(response.json());
if(response.body != 'Error'){
this.message = '';
this.$dispatch('new_message', response.json());
} else{
this.isLoading = false;
}
}, (response) =>{
});
}
}
}
and then I'm trying to get it out like this
chat.vue
export default {
components:{
get_message:getMessage,
add_message:addMessage,
},
data(){
return{
messages:[]
}
},
events:{
'new_message':function(data){
this.messages.push(data);
}
}
}
I'm facing this error in console...any ideas how can I solve this ?
update
If your store is registered with Vue, it seems like it should work. If your $dispatch works outside of the promise, you can try storing this context in another variable
sendData(){
this.isLoading = true;
const that = this;
this.$http
.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms})
.then((response) => {
console.log(response.json());
if(response.body != 'Error'){
that.message = '';
that.$dispatch('new_message', response.json());
} else{
that.isLoading = false;
}
}, (response) =>{
});
}
or just the $dispatch
sendData(){
this.isLoading = true;
const $dispatch = this.$dispatch;
this.$http
.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms})
.then((response) => {
console.log(response.json());
if(response.body != 'Error'){
this.message = '';
$dispatch('new_message', response.json());
} else{
this.isLoading = false;
}
}, (response) =>{
});
}
Taking a guess here, but try calling this instead
this.$store.dispatch('new_message', response.json());
alternatively, your issue could be a scope issue (seeing that this is called from a promise)
if you have a function declared like this in the promise handler then(function(response){this.$store.dispatch('new_message', response.json());}) it might be due to scope
instead you could try using arrow function
then((response) => {
this.$store.dispatch('new_message', response.json());
})

How to get Params from url for Axios GET request?

Before everything, this is not duplicate.
How can i get my Axios parameters from URL for my GET request?
Example:
Link : http://127.0.0.1:8000/callback?Authority=000000000000000000000000000107041762&Status=OK
So parameters are Authority And Status
Authority: How to get this parameters from url
Status: How to get this parameters from url
I'm using laravel & vue.js which the codes are :
callback.vue:
<template>
<div>
TEXT
</div>
</template>
<script>
export default {
name: "callback",
data () {
return {}
},
methods: {
loadData(){
axios.get("api/callback", {
Authority: ,
Status
})
.then(({ data }) => (
console.log(data)
));
},
},
created() {
this.loadData();
}
}
Controller function :
public function order(Request $request){
$MerchantID = 'xxxx';
$Authority =$request->get('Authority') ;
$Amount = 111 ;
if ($request->get('Status') == 'OK') {
$client = new nusoap_client('https://localhost/ices/WebGate/wsdl', 'wsdl');
$client->soap_defencoding = 'UTF-8';
$result = $client->call('PaymentVerification', [
[
'MerchantID' => $MerchantID,
'Authority' => $Authority,
'Amount' => $Amount,
],
]);
if ($result['Status'] == 100) {
return 'Done';
} else {
return 'Error 1';
}
}
else
{
return 'Error 2';
}
You need to use {params: {}} to pass url query to axios.get
axios.get("api/callback", {
params: {
Authority: ''
Status: 'OK'
}
})
.then(({
data
}) => (
console.log(data)
));
You may do this like so:
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
Usage
Example URL:
http://www.example.com/index.php?id=1&image=awesome.jpg
Calling getQueryVariable("id") - would return "1".
Calling getQueryVariable("image") - would return "awesome.jpg".
Taken from here

Resources