Data is not passing on to the controller - javascript

I am getting a problem in passing data to the controller through axios. When I click on the submit button the data doesn't save into database.
save(){
axios.post('/phonebook',this.$data.list)
.then((response) => console.log(response))
.catch((error) => console.log(error)
);
}
Controller request not received.
public function store(Request $request)
{
$pb = new Phonebook;
$pb->name = $request->name;
$pb->phone = $request->phone;
$pb->email = $request->email;
$pb->save();
return $pb;
}
Web.php
Route::resource('phonebook','PhonebookController');
Request should receive and It should store data in the database.
This is my component:
<script>
export default {
props: ['openmodel'],
data() {
return {
list: {
name: '',
phone: '',
email: ''
}
};
},
methods: {
close() {
this.$emit('closeRequest');
},
save() {
axios.post('/phonebook', this.$data.list)
.then((response) => console.log(response))
.catch((error) => console.log(error));
}
}
};
</script>

Thanks everyone for your support. It works now. I was using php version 5.6. When I updated my Php version to 7. It all works now.

Related

Send variable javascript to controller laravel to update vueJS

I´m traying send data from my modal to one controller for update data, but i don´t know how declare my variable and how i must send this variable...
my actual code is:
vuejs
<script>
export default {
data() {
return {
datosUsuario: [],
isOpen: false,
selectedItem: {},
nombreUsuario: nombreUsuario,
};
},
created: function () {
this.cargar();
},
methods: {
cargar: function () {
let url = "/getDatosPersonales";
axios
.get(url)
.then((response) => {
this.datosUsuario = response.data;
})
.catch((error) => console.error(error));
},
actualizar: function(){
let nombreUsuario = document.getElementById('nombre');
let url = "/actualizarDatos";
axios
.post(url)
.then((response) => {
console.log(response);
console.log(nombreUsuario);
})
.catch((error) => console.error(error))
},
setSelectedItem(item) {
this.selectedItem = item;
}
},
};
when i do click in my button this call a function "actualizar"
<input type="submit" class="btn btn-primary" value="Guardar" #click="actualizar">
i was check that if i do click in button go to my controller and it´s ok, but now i need to pass data in request for update, and i don´t know .
thanks so much for help
I get solve my problem, it´s very easy. share my solution
actualizar: function(){
let url = "/actualizarDatos";
axios
.post(url, {
idUsuario: this.datosUsuario.id,
nombreUsuario: this.datosUsuario.nombre,
email: this.datosUsuario.email,
direccion: this.datosUsuario.direccion,
})
.then((response) => {
console.log(response);
})
.catch((error) => console.error(error))
},

Why am I getting a 200 response even though data isn't being stored in the database?

For starters - My Laravel and React.js codebase are separated.
When I login in Postman with login endpoint followed by uploading name of the file with another endpoint (both of them POST requests), the filePath, email and user_id are stored successfully in the db.
However, when I do try this on the browser - I get a 200 but oddly enough, nothing's stored in the db.
In Postman, it somehow detects what user's logged in which allows me to store the aforementioned information into the DB without problems.
What am I doing wrong here in my frontend and backend code that's not allowing me to do this on the browser? I've hit a wall with this one and not sure where to from here.
FYI: The dd($user); returns the correct information.
Please let me know if you need more information :)
Here's my Upload.js file:
import React, {Component} from 'react';
import axios from 'axios';
class Upload extends Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
id: null,
email: ''
};
this.onFormSubmit = this.onFormSubmit.bind(this);
this.onChange = this.onChange.bind(this);
this.fileUpload = this.fileUpload.bind(this);
}
componentDidMount() {
console.log("Inside componentDidMount()");
let id = localStorage.getItem("id");
let email = localStorage.getItem("email");
this.setState({
id: id,
email: email
})
console.log(id);
console.log(email);
}
onFormSubmit(e) {
e.preventDefault();
this.fileUpload(this.state.selectedFile);
}
onChange(e) {
this.setState({ selectedFile: e.target.files[0] }, () => this.state.selectedFile);
}
fileUpload(file) {
const formData = new FormData(document.getElementsByClassName("form")[0]);
const accessToken = localStorage.getItem("access_token").slice(13,-8);
console.log(accessToken);
console.log(this.state.id);
console.log(this.state.email);
console.log(file.name);
formData.append('file',file);
const headers = {
'Authorization' : 'Bearer ' + accessToken,
'Content-type': 'multipart/form-data'
}
axios.post('http://127.0.0.1:8000/api/auth/wall-of-fame', formData, {headers})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
}
render() {
return (
<form encType='multipart/form-data' id="login-form" className="form" >
<input type="file" name="file" onChange={this.onChange}/>
<button type="submit" onClick={this.onFormSubmit}>Upload</button>
</form>
);
}
}
export default Upload;
Here's my FileUploadController.php file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class FileUploadController extends Controller {
public function store(Request $request) {
$user = Auth::user();
// dd($user);
if($user) {
$user_id = Auth::user()->id;
$email = Auth::user()->email;
$filePath = $request->file('file')->getClientOriginalName();
$data = [
'file_path' => $filePath,
'user_id' => $user_id,
'email' => $email
];
DB::table('mydb.photos')->insert($data);
}
return response()->json($user);
}
}
Here's my api.php file:
Route::middleware('auth:api')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'AuthController#login');
Route::post('signup', 'AuthController#signup');
Route::post('wall-of-fame', 'FileUploadController#store');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
Route::get('wall-of-fame', 'FileUploadController#fileUpload');
});
});

How can I check if the user's currently authenticated using Laravel Passport?

In Postman - I'm logging in successfully with login endpoint and after that, I do a file upload which works successfully with the endpoint below. The id and file path get stored successfully in the db.
I can conclude that in Postman after logging in and only attaching one piece of form data (which's the file being uploaded) - that the id and email display correct values in Postman. I can confirm it because if I run the dd($id, $email);, the correct values are returned.
However, on the browser - I'm trying to send up user id and email but I keep getting a 500 error in the logs that says: "Trying to get property 'id' of non-object".
I'm guessing that in my FileUpload controller code (I'm using Laravel passport) that I need to do a check in order to see if the current user's authenticated, but how? I've looked at all the docs, tried a ton of suggestions but to no avail. I'm trying to send Bearer token in my post request but that's not doing it either. What else can I possibly try?
Here's my frontend code:
import React, {Component} from 'react';
import axios from 'axios';
class Upload extends Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
id: null,
email: ''
};
this.onFormSubmit = this.onFormSubmit.bind(this);
this.onChange = this.onChange.bind(this);
this.fileUpload = this.fileUpload.bind(this);
}
componentDidMount() {
console.log("Inside componentDidMount()");
let id = localStorage.getItem("id");
let email = localStorage.getItem("email");
console.log(id);
console.log(email);
this.getId(id);
this.getEmail(email);
}
getId(id) {
console.log("inside getId()");
this.setState({id: id}, () => console.log(this.state.id));
}
getEmail(email) {
console.log("inside getEmail");
this.setState({email: email}, () => console.log(this.state.email));
}
onFormSubmit(e) {
e.preventDefault();
this.fileUpload(this.state.selectedFile);
}
onChange(e) {
this.setState({selectedFile: e.target.files[0]});
}
fileUpload(file) {
const formData = new FormData();
const accessToken = localStorage.getItem("access_token").slice(13, -8);
console.log(accessToken);
formData.append('file', file);
const headers = {
Authorization: 'Bearer ' + accessToken
}
axios.post('http://127.0.0.1:8000/api/auth/wall-of-fame', formData, {headers})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
}
render() {
return (
<form encType='multipart/form-data' id="login-form" className="form" onSubmit={this.onFormSubmit}>
<input type="file" name="file" id="file" onChange={this.onChange}/>
<button type="submit">Upload</button>
</form>
);
}
}
export default Upload;
Here's my backend fileUpload controller code (using Laravel Passport):
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class FileUploadController extends Controller {
public function store(Request $request) {
$filePath = $request->file('file')->getClientOriginalName();
$id = $request->user()->id;
$email = $request->user()->email;
// dd($id, $email);
if (($user = Auth::user()) !== null) {
$data = [
'file_path' => $filePath,
'user_id' => $id,
'email' => $email
];
DB::table('my.db')->insert($data);
return response()->json($user);
}
return "failed";
}
}
Here's login method in controller:
public function login(Request $request) {
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
$user
]);
}
Here's my middleware:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'AuthController#login');
Route::post('signup', 'AuthController#signup');
Route::post('wall-of-fame', 'FileUploadController#store');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
Route::get('wall-of-fame', 'FileUploadController#fileUpload');
});
});

Vuex Chartist display data

I have a problem with display data
this is my App.vue file:
mounted() {
this.$store.dispatch('getLocation'),
this.$store.dispatch('renderChart', this.$el);
},
my store.js looks like that
mutations: {
setLocation (state, { locations, forecast }) {
state.location = locations;
state.forecast = forecast.consolidated_weather.map(item => {
return Number(Math.round(item['the_temp']))
});
state.data.series.push(state.forecast);
console.log(state.data.series)
},
setChart(state, {context, payload}) {
state.chartist = new Chartist['Line'](context, state.data, state.options, state.responsiveOptions)
console.log(context,)
}
},
actions: {
renderChart({commit}, context, payload) {
commit('setChart', {context, payload})
},
getLocation ({ commit }) {
const url = `${API_URL}location/560743/`
axios.get(url)
.then(response => commit('setLocation', {
locations: response.data,
forecast: response.data
}))
.catch(e => console.log(e))
}
}
The data doesn't load when i refresh browser. But when i move this.$store.dispatch('renderChart', this.$el); to created() then the data is displayed but after refresh doesnt load again. It is probably something with lifecycle hooks but im not really sure. Any ideas?

Turbo, adding params to post or other types of Turbo data not working

I am using Turbo which you can find more information about it here: https://www.turbo360.co/docs
What I am trying to do is to attach a parameter to a Post before it is created. In this case I am trying to attach a profile. I am not getting any errors and from what I see the param is going through just fine, but when I log out the post the profile param is not there.
Here is creating the post:
createPost(params) {
const { currentUser } = this.props.user;
if (currentUser == null) {
swal({
title: 'Oops...',
text: 'Please Login or Register before posting',
type: 'error'
});
return;
}
params['profile'] = currentUser;
console.log(params);
this.props
.createPost(params)
.then(data => {
swal({
title: 'Post Created',
text: `Title: ${data.title}`,
type: 'success'
});
})
.catch(err => console.log(err));
}
Here is the action createPost:
createPost: params => {
return dispatch => {
return dispatch(TurboClient.createPost(params, constants.POST_CREATED));
};
},
Here is the TurboClient function createPost:
const postRequest = (resource, params, actionType) => {
return dispatch =>
turbo({ site_id: APP_ID })
.create(resource, params)
.then(data => {
if (actionType != null) {
dispatch({
type: actionType,
data: data
});
}
return data;
})
.catch(err => {
throw err;
});
};
const createPost = (params, actionType) => {
return postRequest('post', params, actionType);
};
Now from here you can see where I log the params, this returns:
Here is what the post looks like once it is created:
It looks like you're trying to create a Post object. In your createPost method you return:
postRequest('post', params, actionType);
By using the word 'post' here you are creating it as a Post object, which has a very specific schema that it follows. If you would like to change that, you could try creating a Custom Object by doing something like this, for example:
postRequest('randomName', params, actionType);
Hope that helps.

Categories