Home > Back-end >  Laravel Breeze Inertia - Vue issue with using Eloquent relationships in the Vue page
Laravel Breeze Inertia - Vue issue with using Eloquent relationships in the Vue page

Time:06-16

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!

-Edit-

I have found a solution that works for me, if anyone is interested in how I have done this, I mapped through the array of Forms and added a new field to the array containing the users name using the Eloquent relationship. Code below for reference:

$forms = Form::orderBy('updated_at', 'desc')->get();
    $forms = $forms->map(function ($form) {
        return [
            'id' => $form->id,
            'username' => $form->user->name,
            'title' => $form->title,
            'created_at' => $form->created_at->format('d/m/Y - H:i:sa'),
            'updated_at' => $form->updated_at->format('d/m/Y - H:i:sa'),
        ];
    });

CodePudding user response:

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

{{ post.user.name }}

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

  • Related