Send array from Laravel and get object in Vuejs using axios - laravel

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

Related

how sort by name in json response

Simple thing i am taking users and want to sort by name. Yea it is very easy
User::where('status_symbol', User::ACTIVE)->orderBy('name')->get()->pluck('full_name', 'id')
full name is attribute from user model
public function getFullNameAttribute() {
return $this->name . ' ' . $this->surname;
}
and results are ok. Now i want send to view (vue) but somehow js sorting again by id as default.
return response()->json(User::where('status_symbol', User::ACTIVE)->orderBy('name')->get()->pluck('full_name', 'id'));
but if i sent without id seems ok, how can make sort by full_name after send response to vue?
axios.get('/api/users/get/all')
.then(response => {
console.log(response.data)
this.reps = response.data
}).catch(e => {
console.error('Failed to load users')
});
Because you are doing pluck over your results, which give you id => full_name results. Your call should be:
User::where('status_symbol', User::ACTIVE)
->orderBy('name')
->get('name', 'surname', 'id')
->only(['full_name', 'id']);

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

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);
});

dd() not working in vue-laravel project axios call.Is it possible to use dump in axios call?

I am using vue with laravel.but my save function not working. So I tried to dump and die the request object but I can't see the request object in the preview. it is blank.
protected function save()
{
$request = Request::all();
dd($request);
$suggestion = new Suggestion();
$suggestion->connection_id = $request['connection_id'];
$suggestion->company_id = $request['company_id'];
$suggestion->module = $request['module'];
$suggestion->description = $request['image'];
$suggestion->save();
return 'success';
}
the axios call is
axios.post('suggestion/save', this.post).then(response => {
this.$swal({
title: 'Success',
text: response.data.message,
type: 'success',
confirmButtonText: 'OK',
});
this.$router.push('/suggestion-list');
})
There are multiple Request classes in Laravel, One thing you can try is the following,
public function controllerFunction()
{
dd(request()->all());
$suggestion = new Suggestion();
$suggestion->connection_id = $request['connection_id'];
$suggestion->company_id = $request['company_id'];
$suggestion->module = $request['module'];
$suggestion->description = $request['description'];
$suggestion->save();
return 'success';
}
So irrespective of your class, the request() function will bring up the appropriate object.
If you get to dump the request then you can confirm that the request is hitting the appropriate controller function, otherwise, the request is going somewhere else. check the network tab in chrome for more details.
Also, make sure you have the appropriate Request class in the use statements.
The correct Request class usage is like following
use Illuminate\Http\Request;
Add request to your function
also add 'use Illuminate\Http\Request'
use Illuminate\Http\Request
public function myFunction(Request $request)
{
dd($request->all());
...
}
hey you can use print() or print_r() to check result
and make sure your this.post has data or not

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;
});
}

Backbone.js Collections not applying Models (using Code Igniter)

I'm attempting to develop a site using CodeIgniter and Backbone.js, but I'm running into an issue when attempting to set Models to a Collection I have called fetch() on. I am using the REST API by Phil Sturgeon, and am receiving a JSON response when using fetch() on the Collection, but no children Models are added to it.
Here's the javascript I'm using:
$(document).ready(function() {
window.Person = Backbone.Model.extend({});
window.People = Backbone.Collection.extend({
model: Person,
url: "/api/content/users/format/json"
});
});
And my CI Controller:
require APPPATH.'/libraries/REST_Controller.php';
class Content extends REST_Controller {
function users_get() {
$users = array(
array('id' => 1, 'name' => 'Some Guy', 'email' => 'example1#example.com'),
array('id' => 2, 'name' => 'Person Face', 'email' => 'example2#example.com')
);
if($users) {
$this->response($users, 200); // 200 being the HTTP response code
} else {
$this->response(array('error' => 'Couldn\'t find any users!'), 404);
}
}
}
And when attempting to fetch() the Models for the Collection via the console like:
peoples = new People();
peoples.fetch();
peoples.models;
It gets the JSON response, but still says 'There are no child objects' (see image):
http://i.stack.imgur.com/e5vZv.png
Any idea what is going wrong? Totally stumped!
Explications
It's normal that people.models is empty directly after the fetch() call, you need to wait the end of the ajax request.
Indeed, fetch() is asynchronous and the Backbone JS documention says :
collection.fetch([options])
[...] The options hash takes success and error callbacks which will be passed (collection, response) as arguments.
Source: http://documentcloud.github.com/backbone/#Collection-fetch
Solution
You need to use :
peoples = new People();
peoples.fetch({
success: function (collection, response) {
// The collection is filled
console.log('Models : ', peoples.models);
}
});

Resources