How to pass data from Vue to Laravel for patch request? - laravel

i'm trying to send a patch request from my Vuetify data-table to Laravel & then to a mySQL DB.
Here's various code pieces from my controller.php, my api.php & the actual Vuetify file:
api.php:
Route::patch('machines/{id}', [
'as' => 'machines/{id}',
'uses' => 'MachineController#update'
]);
MachineController.php
$machines = Machine::find($request->id)->update();
the actual axios patch req. in the .vue file:
Object.assign(this.machines[this.editedIndex], this.editedItem);
axios.patch("machines/" + this.editedItem.id, {
editedItem: this.editedItem
})
In the Telescope payload section i'm getting the updated object, but i'm also getting a message:
"SQLSTATE[23000]:
Integrity constraint violation:
1048 Column cannot be null.
For all the columns.
I have also tried this syntax for a patch method:
if (this.editedIndex > -1) {
Object.assign(this.machines[this.editedIndex], this.editedItem);
axios
.patch("machines/" + this.editedItem.id)
.then(res => {
this.editedItem = Object.assign({}, this.editedItem);
})
.catch(err => {
console.log(err);
});
} else {
this.machines.push(this.editedItem);
}
this.close();
And i tried setting up the controller like this:
$machines = Machine::find($request->id);
$machines->machine_number = $request->input('machine_number');
$machines->machine_name = $request->input('machine_name');
$machines->machine_company = $request->input('machine_company');
$machines->machine_division = $request->input('machine_division');
$machines->machine_center = $request->input('machine_center');
$machines->machine_speed = $request->input('machine_speed');
$machines->save();
But I'm still getting the same error.
Can someone help me out, or at least point me in the right direction?
Thanks!

I have solved my issue: I was passing empty object with my axios.patch() request because i've set it up wrong. I've changed the object's structure to key:value pairs and voila, it worked!

Related

Axios GET return [0, 0, 5] instead of UUIDs from database using Laravel and Vue JS

This problem looked so simple for me when I face with it yesterday! But when I didn't find similar question on google I realized it is not as simple as what I thought!!!So if there is any similar question that I didn't find since yesterday please let me know.
I'm trying to pass data from database using Laravel. I used UUID as primary key for Notifications table instead of auto-increment primary key (this is a default option for notifications table in Laravel!).
I can fetch and read all other columns as what they are but ID column which is UUID type comes as 0 OR 0 OR 5 or just any other single numbers however the real ID can be 1367dc99-ee67-4f0f-b0eb-c2215831d7db.
Frankly, I have no idea what is wrong either with the method I used in the Laravel or in Vue JS axios.
Is there any specific technique that I should use to read UUIDs from backend to frontend? Please help me with this.
I attached codes from Laravel and Vue JS Axios down below. If there is anything missing in my question please let me know.
Laravel Code
$notifications = Notifications::where('notifiable_id', auth()->user()->id)->orderBy('created_at', 'DESC')->get();
return response()->json(
[
"notifications" => $notifications
]
Vue JS Axios GET Method
data () {
return {
loading: false,
unreadNotifications: []
}
},
methods: {
async Notifications () {
this.loading = true
await axios.get('/user/notifications/unreads')
.then((response) => {
this.unreadNotifications = response.data
})
.finally (() => {
this.loading = false
})
}
}
the output is [ 0, 5 ]
If you want to display your id like this : 1367dc99-ee67-4f0f-b0eb-c2215831d7db, then modify your query by :
$notifications = DB::table('notifications')
->where('notifiable_id', auth()->user()->id)
->orderByDesc('created_at')
->get();
return response()->json([
"notifications" => $notifications
]);

get user permissions with laravel vue rest api

I'm trying to get all user permissions with Laravel for backend and vuejs for frontend.
How can i get this from api to vue? what is the best choice?
I tried to get them with below code but shows me error
In the permissionMixin:
import PermissionDataService from '../../Servieces/PermissionDataService'
export default {
methods: {
checkPermission() {
let permissions;
PermissionDataService.get("user_permissions")
.then((response) => {
permissions= response.data;
})
.catch((error) => {
console.debug(error)
});
return hasAccess;
}
}
}
and that is how i used it in main.js:
import permission from "#/core/mixins/permissionMixin";
Vue.mixin(permission);
window.Laravel = this.checkPermission();
console.debug(Laravel)
Vue.directive('can', function (el, binding) {
return Laravel.permissions.indexOf(binding) !== -1;
});
but always shows me this error:
Uncaught TypeError: can't access property "defaults", a.default.axios is undefined
I am totally sure the endpoint is ok
ANY Idea?
Finally solved.
I had to put
window.Laravel = this.checkPermission();
into one of layout files

Laravel + Vue ssr. Prefetch data

I'm trying to make application lavevel + vue with server side render. I have found this manual and it works perfect. Bu there is a small problem. I need fetch data before page loading for SEO issues and I found official vue ssr manual for prefetch. But it does not work. I only see error in the console
entry-client.js:6952 [Vue warn]: Cannot find element: #app.
my entry-server.js
import {createApp} from './app'
export default context => {
return new Promise((resolve, reject) => {
const {app, router, store} = createApp();
router.push(context.url)
router.onReady(() => {
// This `rendered` hook is called when the app has finished rendering
context.rendered = () => {
context.state = store.state
}
resolve(app)
}, reject)
}).then(app => {
renderVueComponentToString(app, (err, res) => {
print(res);
});
})
.catch((err) => {
print(err);
})
}
Are there any idea how solve this problem?
Looks like Promise does not work
Laravel 5.7 and Vue 2.6.6

Vue.js 2 & Axios - Filtering an api for a search feature

I'm trying to filter through a collection of films that i'm retrieving using axios. This is so i can compare it to a search string for a search feature. Everything works fine except when using the computed property it returns Cannot read property 'filter' of undefined" but when i check the vue dev tool it says that the computed property contains the array of films which doesn't really add up. The code is as follows.
created(){
this.fetchFilms();
},
methods:{
fetchFilms(page_url){
let vm = this;
// storing the page url
page_url = page_url || '/api/films'
axios.get(page_url)
.then(response => response)
.then(response => {
this.films = response.data;
vm.makePagination(response.meta, response.links);
})
.catch(err => console.log(err));
},
makePagination(meta,links){
let pagination = {
current_page: this.films.meta.current_page,
last_page: this.films.meta.last_page,
next_page_url: this.films.links.next,
prev_page_url: this.films.links.prev
}
this.pagination = pagination;
}
},
computed: {
filteredFilms () {
return this.films.data.filter((film) => {
return film.film_name.toLowerCase().match(this.searchString.toLowerCase())
})
},
}
This is how the data is returned
films:Object
data:Array[10]
links:Object
meta:Object
Any help is appreciated.
You're probably accessing filteredFilms before the request is done. I don't see any code to wait for the request. You could make filteredFilms check if the data is there and return an empty list if it isn't.

302 Found on Laravel in GET request made by cross-fetch on react

I have a component with a table, when this component mounts I would like to make a request to get data that fills the table.
In my table component:
componentDidMount() {
const { fetchTransactions } = this.props;
fetchTransactions()
}
This came from (I'm using redux):
const mapDispatchToProps = dispatch => ({
fetchTransactions: value => dispatch(fetchTransactions())
})
And the action:
export function fetchTransactions() {
return function (dispatch) {
dispatch(requestTransactions())
return fetch('/getTransactions')
.then(
response => response.json(),
error => console.log('An error occurred.', error)
)
.then(json => dispatch(receiveTransactions(json)))
}
}
When the component mounts, the action is dispatched and the fetch too, but the response is a 302 found as you can see here:
Using the browser it work as I expect:
Any ideas? thank you.

Resources