Laravel api with paginate() does not work with reach native - laravel

I have a laravel api in which I added ->paginate() so I can paginate, and use it by fetching the laravel api in my react native app, so as to apply a load more data when the app is scrolled.
This my laravel api
public function allPerson(Request $request) {
return Person::where('active', 'online')->paginate($request->input('results', 10));
}
Api URL
https://housedata.com/allperson?page=2
React Native
const [personData, setPerson] = React.useState([]);
const getPerson = () => {
axios.get('https://housedata.com/allperson?page=2')
.then(response => {
setPerson(response.data)
console.log(response.data);
});
}
useEffect(() => {
getPerson();
}, []);
<FlatList
data={personData}
keyExtractor={item => item.id}
renderItem={({ item }) => {
return (
<View>
<Text>{item.person_name}</Text>
</View>
);
}}
/>
When I check console.log(response.data); I see the data is been fetch.
Also when I change ->paginate() to get() it is showing the data and working, how can I fix this.
Thanks

the get and paginate method returns data differently the get method returns the data directly where as the paginate method will return a paginate object which contains a data property so to access it you have to do
response.data.data
axios.get('https://housedata.com/allperson?page=2')
.then(response => {
setPerson(response.data.data) // <-- change this
console.log(response.data.data);
});

Related

Send array from Laravel and get object in Vuejs using axios

From Laravel I am sending an array, but on the frontend I receive an object, not sure why.
Maybe I am doing something wrong.
//BACKEND
public function index($course_id){
$courses = CourseTopic::select([
'course_topics.id',
'course_topics.name',
])
->where('course_id', $course_id)
->get()
->groupBy('id')
->toArray();
foreach ($courses as $course_topic) {
// here I have some logic..
}
dd(gettype($courses)); -> here is Array
return response($courses);
}
//FRONTEND
getCourseAreas(){
this.$http.get('/course-area/' + this.course_id)
.then(res=>{
console.log(typeof res.data); -> here is Object
this.course_areas = res.data;
})
},
if you use typeof on a array it returns object
to go safe use ->json on your response to send json formatted data to your frontend

Axios gives undefined while accessing data at Vue's componenet in Laravel

I'm using Laravel and Vue's component, and when i try to access the banners property from response returned by axios in vue component it gives me undefined.
I am accessing the perperty like response.data.banners
I'm returning data from controller in following way:
public function getBanners(Request $request){
return response()->json(['
banners'=> BannerImage::active()->get()
]);
}
Here is how i am accessing axios response
<script>
export default {
data: function() {
return {
banners: []
}
},
mounted() {
axios.get("getBanners").then((res)=> {
console.log(res);
console.log(res.data);
console.log(res.data.banners);
this.banners = res.data.banners;
});
console.log('Component mounted.')
}
}
</script>
Response by axios
All is working before accessing the banners property. Is there anything i am not doing correct ?
You have an linebreak ↩ between ' and banners, which is shown in the console line 2 "↩ banners":
Problem
public function getBanners(Request $request){
return response()->json([' // <-- ↩ line break
banners'=> BannerImage::active()->get()
]);
}
Correct
public function getBanners(Request $request) {
return response()->json([
'banners' => BannerImage::active()->get()
]);
}

How to check request is axios in laravel

export const category_load = ()=>{
return async (dispatch) => {
await fetch('https://example.com/api/user/categorylist')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}
}
I sent the axios request to the server.
Here is the server code.
...
if($request->ajax()){
return $Categories;
}
return view(Route::currentRouteName(), compact('Categories'));
If I sent ajax it returns $Categories but I sent axios it returns view.
I have to check axios request like ajax and return $Categories.
How to solve this?
The above answer will work, but it's insecure what if someone gets to know why are you using the additional param and they use it on the browser direct?
Instead, pass header which by default Laravel will read to check if the incoming request is ajax or not.
axios.get(url, {
body:{},
headers: {
"X-Requested-With": "XMLHttpRequest",
},
})
Now you can simply do $request->ajax() in the controller and it will work.
API endpoints are not meant to be used to return views. :) Use non API endpoints to return views.
BTW, with your current implementation you can do this way:
Send an extra parameter, for example, api=true with your Axios request endpoint, as:
export const category_load = ()=>{
return async (dispatch) => {
await fetch('https://example.com/api/user/categorylist?api=true')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}
Now, in your controller, you can check if the api parameter is set or not. If it's set you can just return the categories like you're doing for the ajax request, as:
// return $Categories if the request is from Axios or Ajax
if($request->ajax() || $request->api == true) {
return $Categories;
}
return view(Route::currentRouteName(), compact('Categories'));

PUT errors in Vue

I'm trying to update data using laravel. I'm not sure why I can't access the PUT api. I tied so switch the api to store the data vs update and that works. I can't see anything wrong with the code.
Here is the api router
Route::put('product', 'ProductController#update');
here is the controller
public function update(Request $request, $id)
{
$product= Product::findOrFail($id);
$product->update($request->all());
return ['message' => "Success"];
}
Here is the vue.js
methods: {
updateProduct(id){
this.$Progress.start();
this.form.put('api/product/'+this.form.id)
.then(() => {
// success
$('#addNew').modal('hide');
Swal.fire(
'Updated!',
'Information has been updated.',
'success'
)
this.$Progress.finish();
Fire.$emit('AfterCreated');
})
.catch(() => {
this.$Progress.fail();
});
},
In the Vue component I have a modal with a form
<form #submit.prevent ="editmode ? updateProduct() : createProduct()">
The error I'm getting is
405 (Method Not Allowed)
The error I was getting was in the api router.
Route::put('product/{id}', 'ProductController#update');

Laravel & vue axios get method returns Getters & Setters?

I am new in Vue.js and trying to use axios to fetch data from Laravel API.
The function in backend returns an array of arrays as:
public function getPersonTypes()
{
$data = [];
$personTypes = config('codeechoo.documentation.config.personTypes');
foreach ($personTypes as $id => $type) {
$data[] = [
'id' => $id,
'name' => trans($type)
];
}
return response()->json($data);
}
And the Vue function in methods is:
fetchPersonTypes() {
axios.get(route('api.documentation.person.types'))
.then((response) => {
console.log(response.data);
this.personTypes = response.data;
});
}
But the console show the result as an array of objects like:
id: Getter & Setter
name: Getter & Setter
So how can I get the real values of id, name props ?
You can extract the data by stringifying and then parsing it back:
let personTypes = JSON.parse(JSON.stringify(response.data));
console.log(personTypes);
What you will see in the console now is the whole data without the getters and setters.
I think you should call the route url directly.
NOTE: because in axios the default baseURL is already set, you don't need to type base url, only the path.
Example: instead of axios.get(http://yoursite.com/you/path), just type axios.get('your/path').
fetchPersonTypes() {
axios.get('your/path').then(({data}) => {
console.log(data);
this.personTypes = data;
});
}

Resources