how sort by name in json response - laravel

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']);

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

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

Load cities from state laravel

I am working with laravel, right now, i am making an user registry Form, i am relating the state and its cities, so, i need to change a select field values according the state that user chooses.
I have something in the form:
{{ Form::select('city', $city, array('id', 'city')}}
If i use the {{Form::select}} fields in conventional way it charges all the cities from one state, so, when the user select a state, it must change the list of cities in the select field.
I searched but i didn't find any. How can i do that?
thanks.
You can use ajax with jQuery.
In your view set an event when the state change, like this:
$(document).on('change', '#state_id', function (e) {
// empty the select with previous cities if we have.
$('#cities').empty();
$.ajax({
type: "POST",
dataType: "json",
// actions is a controller
// cities is a method of actions controller
url : "{{ URL::to('actions/cities') }}",
//here we set the data for the post based in our form
data : $('#MyFormID').serialize(),
success:function(data){
if(data.error === 0 ){ // all was ok
for (var i = 0; i < data.cities.length; i++) {
$('#cities').append("<option value='"+data.cities[i].id+"'>"+data.cities[i].city_name+"</option>")
}
}else{
alert(data);
}
},
timeout:10000
});
});
actions/cities controller
//remember, this is a post method
public function postCities(){
// validate
$validator = Validator::make(Input::all(),
array(
'state_id' => 'required|integer'
));
if ($validator->fails()) {
return Response::json(array('error' => 1, 'message' => 'State is required'));
}
//City is your model, I assumes that you pkey is ID and the city name is city_name and your fkey is state_id
$cities = City::where('state_id', '=', Input::get('state_id'))->get();
return Response::json(array('error' => 0, 'cities' => $cities));
}
public function getCities($province_id)
{
$cities = Cities::where('province_id', '=', $province_id)->get(['id', 'name']);
return Response::json(array('error' => 0, 'cities' => $cities));
}
You might want to check a sample vue component that ships with my package Laravel Cities that performs exactly what you are trying to build.
This is a simple package that allows you seed localy all the cities of any country on the world (provided by geonames.org) and perform any query with the provided Eloquent model. It exposes an HTTP API and a vue component that allows you to select any city through a series of steps.
You can insert it in your forms like any other input field:
<form action="post-url" method="POST">
<geo-select></geo-select>
<!-- Add more form fields here... -->
<input type="submit">
</form>
With the provided Eloquent model You can perform queries like this:
// Get the States of USA in aplhabetic order
Geo::getCountry('US')
->children()
->orderBy('name')
->get();
Sorry, no demo yet, but you can check some sceenshots on the github page...

Laravel Mail::send with a mail->to loop

I try to fill the receiver of an email from database. If I write the adress direct to $mail->to everything works fine but not with this code?:
$users = User::where('message_receiver','=',true)->get();
$data = array(
'url' => Config::get('app.url'),
'name' => 'test'
);
Mail::send('emails.message', $data, function($mail) use ($users)
{
$mail->from('test#localhost.de','test#localhost.de');
foreach ($users AS $user) {
$mail->to($user->email, $user->firstname.' '.$user->surname);
}
$mail->subject('New Message');
});
print_r($user->email) in the loop dumps the correct adress!
I never work with Laravel, but by this link http://bundles.laravel.com/bundle/Messages
As I understand, to send emails to multiple email addresses, you have to add all addresses into array first, then pass that array to $message->to() method, don't you?
And this is a sample from that link:
Message::send(function($message)
{
$message->to(array('someone#gmail.com', 'email#address.com' => 'name'));
$message->cc('more#addresses.com');
$messages->bcc(array('evenmore#address.com' => 'Another name', 'onelast#address.com'));
$message->from('me#gmail.com', 'Bob Marley');
$message->subject('Hello!');
$message->body('I really like spamming people!');
});
So, in my idea, you should try to make array from $users and then pass it to the method, something like this:
Mail::send('emails.message', $data, function($mail) use ($users)
{
$mail->from('test#localhost.de','test#localhost.de');
foreach ($users AS $user) {
$receivers = array_add($receivers, $user->email, $user->email);
}
$mail->to($receivers);
$mail->subject('New Message');
});
I'm not sure if I used array correctly, but I think you have alredy know how to do that.

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