1

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...)

3
  • What does getSomestringFromPerson() do? Commented Feb 17, 2017 at 21:58
  • 2
    @jackel414 "function getSomestringFromPerson() which is operating on the Model Person and returning a string" It does that :P Commented Feb 17, 2017 at 22:02
  • @TimLewis Haha, fair enough. I was trying to suss out whether it was manipulating data or just parsing a string (something that would be easy to do in JS), but I supposed it may not matter. Commented Feb 17, 2017 at 22:09

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OK. That was what I meant with "run the function in the Controller and include the result in the AJAX response"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.