Reputation: 113
I have a relation one to many between users table and areas table , when i return profile data i get area_id from users table, i need to get area name using models. Is there a way to get area name in profile view ? I tried to call model function in show.vue but it is not working.
User.php
public function area()
{
return $this->belongsTo(Area::class);
}
Area.php
public function users()
{
return $this->hasMany(User::class);
}
show.vue
<template>
<app-layout>
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Profile
</h2>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Area :
</h2>
</template>
<div>
<div class="max-w-7xl mx-auto py-10 sm:px-6 lg:px-8">
<div v-if="$page.props.jetstream.canUpdateProfileInformation">
<update-profile-information-form :user="$page.props.user" />
<jet-section-border />
</div>
<div v-if="$page.props.jetstream.canUpdatePassword">
<update-password-form class="mt-10 sm:mt-0" />
<jet-section-border />
</div>
<div v-if="$page.props.jetstream.canManageTwoFactorAuthentication">
<two-factor-authentication-form class="mt-10 sm:mt-0" />
<jet-section-border />
</div>
<logout-other-browser-sessions-form :sessions="sessions" class="mt-10 sm:mt-0" />
<template v-if="$page.props.jetstream.hasAccountDeletionFeatures">
<jet-section-border />
<delete-user-form class="mt-10 sm:mt-0" />
</template>
</div>
</div>
</app-layout>
</template>
<script>
import AppLayout from '@/Layouts/AppLayout'
import DeleteUserForm from './DeleteUserForm'
import JetSectionBorder from '@/Jetstream/SectionBorder'
import LogoutOtherBrowserSessionsForm from './LogoutOtherBrowserSessionsForm'
import TwoFactorAuthenticationForm from './TwoFactorAuthenticationForm'
import UpdatePasswordForm from './UpdatePasswordForm'
import UpdateProfileInformationForm from './UpdateProfileInformationForm'
export default {
props: ['sessions'],
components: {
AppLayout,
DeleteUserForm,
JetSectionBorder,
LogoutOtherBrowserSessionsForm,
TwoFactorAuthenticationForm,
UpdatePasswordForm,
UpdateProfileInformationForm,
},
}
</script>
Upvotes: 8
Views: 5432
Reputation: 99
Controller.php:
$doctors = User::with('area')->paginate(5);
Vuefile.js
{{user.area.name}}
Upvotes: 1
Reputation: 1
I had the same problem, but finally i found another trick, I defined another method in my model and added an attribute
In your case: Try this: Area.php
class Area extends Model
{ ....
$appends = ['users'];
public function users()
{
return $this->hasMany(User::class);
}
// define a methode getUsersAttribute()
public function getUsersAttribute(){
return $this->users()->get();
}
Upvotes: 0
Reputation: 5943
You need to load all relationships you want to display manually. Unlike in Blade you can’t just access the relationship with $user->area
because $user
is not an Eloquent instance but what you are returning as JSON to your Vue instance.
From your controller call $user->load('area')
. This will make area
available to you.
Upvotes: 10