Jonathan Herrera
Jonathan Herrera

Reputation: 6104

Retrieve Eloquent Model function in JavaScript

In Laravel, I have an Eloquent Model Person and a function getSomestringFromPerson() which is operating on the Model Person and returning a string. Now I have an AJAX request whose response is a collection of Persons. Until here I know what to do.

Now, in the JavaScript I would like do display the result of getSomestringFromPerson() for each Person in the response. Is that possible? If yes, how? Or do I have to run the function in the Controller and include the result in the AJAX response? (That looks a bit cumbersome to me...)

Upvotes: 1

Views: 1017

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

In the controller that handles the AJAX request, I assume it gets a collection of People like something like this (at a bare minimum):

public function handleAjax(Request $request){
    $people = People::get();

    return response()->json(["people" => $people], 200);
}

And then in your JS a function for handling the response:

$.get(URL, function(data){
    console.log(data); // Collection (js object) of `People` models.
});

In your handleAjax function, you would loop over each of your People and assign a property to hold the value of $person->getSomestringFromPerson():

foreach($people AS $person){
    $person->someString = $person->getSomestringFromPerson();
}

Then, in your Javascript code, you would be able to access it like so:

for(var person in data.people){
    console.log(data.people[person].someString); // Should return the expected value of `$person->getSomestringFromPerson();` as defined in your function.
}

From there, you should be able to do whatever else it is you'd need to do with your data.people object.

Upvotes: 3

Related Questions