1

First off, I have been using Laravel for a while now and only recently opted to try out the Inertia Vue.js build as I wanted to make a SPA...

However, I cannot seem to find how Vue handles Eloquent relationships.

An example of what I mean would be in "vanilla" laravel breeze, I could setup a relationship between my users table and the posts table. Now, in normal Laravel I could then open my Blade page and access the user who created a post by using the code: $post->user->name

In the Inertia Vue version. Since I need to send over the array of all posts as a prop to the Vue page, it wont count as an Eloquent object, which means I cannot use $post->user->name ... I have looked at the inertia documentation (from what I could find) and have not been able to find the way they managed to perform this type of request.

If this is simply not possible in the Inertia version, I will simply go back to the "vanilla" laravel, as having Eloquent Relationships is a must for me and I can sacrifice the "instant" page rendering from the SPA.

Any help would be appreciated!

1 Answer 1

1

You can modify the data with API Resource. Here's example:

YourController.php

public function index() {
   return PostResource::collection(Post::with('user')->get());
}

PostResource.php

public function toArray($request) {
    return [
        'id' => $this->id,
        'title' => $this->title,
        'user' => [
              'name' => $this->user->name,
              'email' => $this->user->email,
         ],
    ];
}

Access it like you format it on API resource

Index.vue

// for post in posts
<li>{{ post.user.name }}</li>

From my experience, always limit the return value of your resource if you have sensitive data like CC number or address of user. Because return value is visible from client side

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

1 Comment

Actually, I will convert my fix and use yours instead! Thank you. Just realized yours would be way more efficient and more re-usable!

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.