I started experiencing something strange in my laravel.vuejs application today. When i pass a JS object from vuejs frontend to laravel backend, it gets converted to array. For example, in vuejs
data() {
return {
user: {
name: '',
email: '',
age: ''
},
}
},
methods: {
submit(){
axios.post(this.api + '/test', {
user: this.user
}).then((res) => {
console.log(res.data)
})
}
},
In my laravel controller, print_r($request->user) shows the object as an array.
Array
(
[name] =>
[email] =>
[age] =>
)
How do i fix this? I am using laravel5.8 NB: I noticed this started happening after i ran composer update. Could this be the cause?
NB: After creating the model, I get back a response of array instead of JSON, even after returning the response as JSON. That is the problem.
Object concept doesn't exist in HTTP protocol and you can't send your data with requests as an object. you can get the input as json object and decode it, but that will be a StdClass object. So, you can assign the request array to the user model and use it as an object.
Example:
Suppose you created a User model and you want to assign the array as an attribute.
$user = new User($request->user);
// or
$user = new User();
$user->fill($request->user);
// or
$user = new User();
$user->name = $request->user['name']
$user->age = $request->user['age']
...
Note: It's better to validate the inputs before assign to the user object. you can do it clearly with Form Requests