kevinwakhisi's avatar

Display Data in vue

i am looking for a way i can solve this issue where i can display data in a one to one relationship from my model.

the error message i get is :-

can't access property "location", user.detail is undefined

my current binding model is :-

<h1 class="px-2 text-sm">{{user.detail.location}}</h1>

The users table is :-

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('is_suspended')->default(false);
            $table->string('password');
            $table->rememberToken();
            $table->foreignId('current_team_id')->nullable();
            $table->text('profile_photo_path')->nullable();
            $table->timestamps();
        });
    }

whereas the details table is:-

public function up()
    {
        Schema::create('details', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained();
            $table->string('location');
            $table->string('mobile_no');
            $table->string('mobile_no_2')->nullable();
            $table->text('current_agency')->nullable();
            $table->timestamps();
        });
    }

I have the models defined as :-

user model

 public function details()
    {
        # code...
        return $this->hasOne(Detail::class);
    }
public function user()
    {
        # code...
        return $this->belongsTo(User::class);
    }

since am using inertia vue js for the jetstream scaffolding the controller is detailed as so:-

public function index()
    {
        # code...
        $Users=User::all();

        return Inertia::render('Users/Show',[
            'users' => $Users
        ]);
    }

i know that i have posted alot of information but i would like to know my mistakes in this

0 likes
3 replies
rodrigo.pedra's avatar
Level 56

Try this two changes:

1 - On your User model add this to the detail relation:

public function details()
{
    return $this->hasOne(Detail::class)->withDefault();
}

->withDefault() will return an empty model even if a user has no associated detail model. It is useful to prevent accessing a sub-property from the user's detail property as it won't be null.

2 - Then on your controller, eager load the relation:

public function index()
{
    # code...
    $Users=User::with(['details'])->get();

    return Inertia::render('Users/Show',[
        'users' => $Users
    ]);
}

This will eager load the details relation for each user model, so when inertia converts it to a JavaScript object it will have the details property

1 like
kevinwakhisi's avatar

Damn I can't believe it ...just worked. I think I should get back to my books now😅. This worked for me

Please or to participate in this conversation.