Laravel API Eloquent Where Clause with Vue not working - sql

My question is, why doesn't my where clause work?
I use a Laravel API for my vue (with vuex) project.
Here's the Controller function
public function specific_client(Request $request) {
$id = $request->id;
return JsonResource::collection(
Measurement::where('client_id', '=',$id)
->with(['clients', 'measurement_data'])->get());
}
I also use vuetify, this is how I get the client_id :
<v-select v-model="cnr" :items="clients" item-text="clientnumber" item-value="id" :hint="cnr" solo></v-select>
My store.js :
fetchClientMeasurements({commit}, cnr) {
axios.post("http://localhost:8000/api/clientnr", cnr)
.then(response => {
console.log(response.data.data);
console.log(cnr);
commit("setMeasurements", response.data.data);
});
},
My API Route :
Route::post('clientnr', [MeasurementController::class, 'specific_client']);
When I console log "cnr" I get back the correct ID but I don't get any data back. If I replace $id in the where clause I do get back the correct information. I feel like it is a stupid mistake I made somewhere, but that's what I'm here for.

In your axios request, you need to label the id parameter.
axios.post("http://localhost:8000/api/clientnr", cnr)
should be
axios.post("http://localhost:8000/api/clientnr", {id: cnr})

Related

fill datatable with vueJS

i´m trayin to fill my data table with vueJS and all my data from DB. I´m usign this library:
https://jamesdordoy.github.io/laravel-vue-datatable
It´s ok if i use this in my controller:
User::all()
return response()->json($query);
and in my component:
<div class="">
<data-table :data="data" :columns="columns" #on-table-props-changed="reloadTable"></data-table>
</div>
this library contain method to sortBy, orderBy, search by name, etc... with this:
use JamesDordoy\LaravelVueDatatable\Http\Resources\DataTableCollectionResource;
public function index(Request $request)
{
$length = $request->input('length');
$sortBy = $request->input('column');
$orderBy = $request->input('dir');
$searchValue = $request->input('search');
$query = User::eloquentQuery($sortBy, $orderBy, $searchValue);
$data = $query->paginate($length);
return new DataTableCollectionResource($data);
}
but if i use this in my controller in laravel 8 returned me:
Call to undefined method App\Models\User::eloquentQuery()
i don´t know if this it means to use get(), all().
Also, if i´m not use this and i to do all search manually, for example:
if(isset($sortBy)){
$query = User::all()->sortBy($sortBy);
$data = $query->paginate($length);
}
return response()->json($query);
returned me that:
Method Illuminate\Database\Eloquent\Collection::paginate does not exist
if i removed paginate and return $query, return all my data en my web browser console in network tab, but my table it´s empty...
for back-end i´m using laravel-8
in my web browser console return this message:
Invalid prop: type check failed for prop "data". Expected Object, got Array
if i change :data in my component for :items error in web browser console disappear
i don´t understand that i´m doing wrong for in one case i can fill my table and in other not...
Thanks for read and help me
i resolve my question with this:
$query = \DB::table('users')->orderBy($sortBy, $order)->paginate(10);
with model i can´t

nuxt watchQuery not working on update route with new query [duplicate]

This question already has answers here:
How to access current route name reactively in Vue Composition API in TypeScript?
(3 answers)
Closed last month.
when i add a new query using $router.push to route Nuxt watchQuery not working and asyncData not fetching api and remount children components. please attention to "New query" and not exist any query by default.(after created new query and then exists query every things are correct and watchQuery works correctly.)
example.com/some-param ----> example.com/some-param?brand=x (not working watchQuery)
example.com/some-param?brand=x ----> example.com/some-param (correct watchQuery)
change_brand: function () {
const vm = this;
/*** selected_brands = [] is an array defined in data ***/
let q = { ...vm.$route.query };
if (vm.selected_brands.length > 0) {
q.brands = vm.selected_brands.join("-");
} else {
delete q.brands;
}
vm.$router.push({
name: "search-slug",
params: vm.$route.params,
query: q,
});
},
As Nuxt documentation says here:
Warning: The new fetch hook introduced in 2.12 is not affected by watchQuery. For more information see listening to query string changes.
I used the following watcher to make fetch hook listen to route query changes:
export default {
watch: {
'$route.query': '$fetch'
},
async fetch() {
// Called also on query changes
}
}
Reference: https://nuxtjs.org/docs/2.x/features/data-fetching#listening-to-query-string-changes

Vue axios delete request not working. How do I fix it?

Im having issues with delete request, my post, get are working fine.
What am I doing wrong?
removeUser(id) {
axios.delete('https://jsonplaceholder.typicode.com/users' + id)
.then(function(response) {
const user = response.data;
this.users.splice(id, user);
});
if response.status === 204, then delete is succeed.
for the client, here is an axios example, notice there is a ' after users
destroy() {
return request.delete('/api/users/' + id)
}
for the server, here is an Laravel example:
if( $article->delete() ) {
return response()->json(null, 204);
} else {
abort(409);
}
I can see only 1 problem on the code you provided.
You're trying to modify the Vue instance $data users object by executing this.users.splice(id, user);. But you're inside the callback function and this no longer represents the Vue instance.
To fix this & make the users object actually modify after the response comes you'll need to do it like this :
removeUser(id) {
let that = this;
axios.delete('https://jsonplaceholder.typicode.com/users' + id)
.then(function(response) {
const user = response.data;
that.users.splice(id, user);
});
Now , I don't have any code from the back-end so I'll just make some assumptions :
The route might not be well defined > if you're using NodeJS then you should check your routes , it should look like this :
router.route('/users:id').delete(async function(req,res,next){ /* ... */ });
You might have a route problem because / is missing before the user value
1 hint : Again , if you're using NodeJS , you could use this inside your .delete route :
res.status(200).json({ errorCode : null , errorMessage : null , users : [] });
To see if you're receiving it on front-end.
I think you do need to append the trailing '/' to the URL, that way the URL is properly formed, such as "https://jsonplaceholder.typicode.com/users/123" (rather than "users123" at the end).
Aside from that, the first parameter to Array.prototype.splice is the position where item removal should begin. The second (optional) parameter, deleteCount, is the number of items to remove. Beyond deleteCount, you can pass a collection of objects which are to be inserted after the start position and after items have been removed.
You just need to find the object in your this.users array and remove it. If you want to use Array.prototype.splice for that, then you can use Array.prototype.findIndex to find the index of the user in the array then remove it:
// Find the index of the item to remove
const indexOfUserToRemove = this.users.findIndex(u => u.id === id);
// Call splice to remove the item
this.users.splice(indexOfUserToRemove, 1);

vue-router query parameter as array with keys

I need to generate a vue-router link that contains an array with string keys as a query parameter.
I want the resulting URL to look like
url?param[key]=value
I need these kinds of query parameters to match an existing backend infrastructure, so renaming/refactoring them is not an option.
I've tried to use a router-link like the one below, but the param object just get's serialized as %5Bobject%20Object%5D. Maybe there is an option to change the way this object is serialized within vue-router?
<router-link :to="{name: 'xyz', query: {param: 'value'}}">link</router-link>
Does anyone have helpful input? Thank you :)
After spending some time vue-router GitHub issues and their docs, I figured it out.
When creating your RouteConfig, import qs and set the parseQuery and stringifyQuery methods as follows:
parseQuery: (query: any): object => {
return qs.parse(query);
},
stringifyQuery(query: any): string {
let result = qs.stringify(query, {encode: false});
return result ? ('?' + result) : '';
}
It is important to include {encode: false}, otherwise the square brackets will get URL encoded.
Addition to Martin's comment,
Exact Router config should be :
// https://github.com/ljharb/qs
import qs from 'qs';
const router = new Router({
routes: [
// ...
],
// set custom query resolver
parseQuery(query) {
return qs.parse(query);
},
stringifyQuery(query) {
var result = qs.stringify(query);
return result ? ('?' + result) : '';
}
});
and query parameters inside routes will be automatically converted url string and parsed as an object when accessing $router.query .

Instant Search with keyup vuejs and laravel

I tried to build an instant search using vuejs and laravel 5.3 but somehow It wont work with no errors showing
Controller (fullcode https://pastebin.com/6mQ4eWTf) :
public function index(Request $request) {
$search = $request->search;
$items = Staff::where('nama', 'LIKE', '%'.$search.'%')->paginate(5);
$response = [
'pagination' => [
'total' => $items->total(),
'per_page' => $items->perPage(),
'current_page' => $items->currentPage(),
'last_page' => $items->lastPage(),
'from' => $items->firstItem(),
'to' => $items->lastItem()
],
'data' => $items
];
staff.js method (fullcode https://pastebin.com/NDxzqsyp) :
methods: {
getVueItems: function (page) {
this.$http.get('/staffitems?page=' + page + '&search=' + this.search).then((response) => {
this.$set('items', response.data.data.data);
this.$set('pagination', response.data.pagination);
});
setTimeout(this.getVueItems, 5000);
},
Blade (fullcode https://pastebin.com/6uDZRryE) :
<input v-on:keyup.enter="getVueItems" type="text" class="form-control" name="search" placeholder="Cari..." v-model="search"/>
Routes :
Route::get('/staffcrud', 'StaffController#Crud');
Route::resource('/staffitems', 'StaffController');
The data correctly shown (tested by getting json response from /staffitems?page=1&search=jon with or without search value), but somehow when I do type words to search in input search column, nothing happened as soon as i finished typing, probably event handling in blade are wrong or my method in staff.js any solution for this?
You should add the debounce in your mounted() method:
mounted() {
this.getVueItems = _.debounce(this.getVueItems, 5000); // i'm using lodash here.
}
To build a really effective instant database search you should consider using pusher and laravel echo together with vuex
You can check out this out >>> Ethiel Adiassa's Live Search Tutorial with laravel and pusher
In your blade template use only:
v-on:keyup='vueGetItems'
Because your instant search is firing only on enter key up. I hope this will work or contact me to get full working code.