1

I'm doing a project where every user can be assigned in a designation.

I did my work by using three model: User, Designation & UsersDesignation

The table structures are:

User:
id      name        email       password
---     -----       -----       --------
1       User 1      [email protected]   kjasdkfjla
2       User 2      [email protected]   fksdjfghal
3       User 3      [email protected]   ghhaljaljl

Designation:
id      name
---     -----
1       Faculty
2       Lecturer
3       Lab Instructor

UsersDesignation:
id      userId      designationId
---     ------      -------------
1       1           2
2       2           1
3       3           3

But I'm facing difficulty to get the designation of user from user object by establishing relationship.

I've tried in my Model so far:

User(model):
public function userDesignation()
{
    $this->hasOne('App\UsersDesignation', 'id', 'userId');
}

UserDesignation(model):
public function user()
{
    $this->belongsToMany('App\User', 'userId', 'id');
}
public function designation()
{
    $this->belongsTo('App\Designation', 'designationId', 'id');
}

Actually I want to show the user profiles from user model with his/her designation. But the above way didn't work. I've no idea how to make this relation.

This is my view file:

<div>
    {{ $user->userDesignation->designationId }}
</div>

The error I get every time

ErrorException (E_ERROR) App\User::userDesignation must return a relationship instance. (View: ....\resources\views\profiles\show.blade.php)

I badly need this help!

1
  • Does a user only have 1 possible destination? Commented Dec 3, 2017 at 20:46

2 Answers 2

3

If a User can only have 1 possible designation, you don't need a pivot table(UsersDesignation table).

Just put a designation_id in the users table and use the belongsTo and hasMany relationships.

User

public function designation()
{
    return $this->belongsTo('App\Designation');
}

Designation

public function users()
{
    return $this->hasMany('App\User');
}
Sign up to request clarification or add additional context in comments.

2 Comments

hasOne() and not hasMany() relationship
Not if a designation can have multiple users.
0

Probably you need use a relationship many to many.

Example:

Table structures:

users:
id
name
email
password

designations:
id
name

designation_user
id
designation_id
user_id

Your model relationships

App\User:

public function designations()
{
    return $this->belongsToMany('App\Designation');
}

App\Designation:

public function users()
{
    return $this->belongsToMany('App\User');
}    

To get the user's designations your call should look like this:

<div>
    @foreach($user->designations()->get() as $designation)
        {{ $designation->name }}
    @endforeach
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.