0

I have a model called Exercise, that belongs to Topic, and a Topic belongs to a Subject.

With

Exercise::with('topic')->get()

I can access properties from the current topic of the exercise inside Vue. What can I do to return also the data from the subject that the topic that my exercise belongs to?

If I was able to use just blade template, I would just call:

{{$exercise->topic->subject->name}}

But the thing is that I'm passing everything as a json to work with the data in a datatable with vue.

One solution is to also pass Subject::all to my view, and use the subject_id inside the exercise>topic with vue:

@{{subjects[exercise.topic.subject_id].name}}

I'm looking for a better and cleaner solution than that. Is there a Laravel method, like multiple with's with multiple relations? Something like:

Exercise::with('topic')->and('topic')->with('subject')->get()

Thank you!

7
  • 1
    Take a look at github.com/spatie/laravel-fractal - seems like you're in need of a more robust API solution. Commented Feb 28, 2019 at 4:07
  • @Trent I'm reading it... Do you really think that it'll be necessary? Commented Feb 28, 2019 at 4:12
  • That's up to you to decide, a serializer like fractal will allow you to define very light serializsed objects (just exercise for example), then use ->includes to get all the other data you want only when you need it. Note: fractal will add some processing overhead Commented Feb 28, 2019 at 4:19
  • @Trent But I'll need to create transformers for every complex data structure? Commented Feb 28, 2019 at 4:23
  • @Trent Isn't there a laravel based solution? Because I'm in a hurry with that project so I don't want to create more and more layers of data processing... But I also don't want to do ugly solutions as the one that I've pointed out in the post! Commented Feb 28, 2019 at 4:26

1 Answer 1

1

If you want to get data with the relation of topic belongs to subject so,

Try this:

Exercise::with('topic.subject')->get();

I hope it would be helpful.

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

Comments

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.