Laravel: Relation between three model - php

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 u1#em.com kjasdkfjla
2 User 2 u2#em.com fksdjfghal
3 User 3 u3#em.com 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!

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');
}

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>

Related

show data from 2 tables laravel 6

I have a problem showing data from 2 tables with an id, in laravel 6. My tables are "users" and "companies".
users
id
name
last name
companies
id
company
address
id_user
Model user
public function company()
{
return $this->hasOne('App\Company','id_user','id');
}
Model company
public function user()
{
return $this->belongsTo('App\User');
}
Controller
public function show($id)
{
$companies = Company::with('user')->find($id);
return view('clients.show', compact('companies'));
}
view
$companies->company
but the problem is that is not showing data from users table, can someone help me?
The foreign key name for user in companies table should be 'user_id' not 'id_user'
If you want to use custom column name make sure you pass it to the second argument of the relationship.
Model company:
public function user()
{
return $this->belongsTo('App\User', 'id_user');
}

Laravel Multiple One To One Relationship In User Model

im trying to create a one to one relationship with the table user,student and teacher. The problem is, when i run LARAVEL TINKER, app\user::find('a123')->teacher it displays the b345 data and doesnt display NULL. New in Laravel. Thanks
Below is the table with their PK.
User table
user_id | type
a123 | 1
b345 | 2
Student table
student_id| name
a123 | Danny
Teacher table
teacher_id| name
b345 | Mr.Mark
and this BELOW is the models.
User Model
protected $primaryKey = 'user_id';
public function student(){
return $this->hasOne(student::class,'student_id');
}
public function teacher(){
return $this->hasOne(teacher::class,'teacher_id');
}
Student Model (Teacher model is just the same with teacher_id as PK)
protected $primaryKey = 'student_id';
public function User()
{
return $this->belongsTo(User::class,'user_id');
}
From you description, student should belongs to user, also teach
In User Model
public function student(){
return $this->hasMany(Student::class,'student_id');
}
In Student Model
public function user(){
return $this->belongsTo(User::class,'student_id');
}

Laravel 5.4 relationship 2 tables 3 id

I work with laravel 5.4, and I want receive information from my relations tables.
I have 3 tables in phpmyadmin
ATHLETES
ID
FIRST_NAME
LAST_NAME
TYPES
ID
NAME
SLUG
ATHLETES_TYPES
ID
TYPE_ID
ATHLETE_ID
I have 3 models
ATHLETE
TYPE
ATHLETEBYTYPE
How do I need to make the relations models to have name and slug from my table TYPES, with my id from my table athletes?
Thank you.
For this you just need 2 model file ATHLETE and TYPE and use many to many relation.and then you can use ATHLETES_TYPES table as pivot table.
for implement this :
first add this method to ATHLETE model file :
public function types()
{
return $this->belongsToMany(TYPE::class,'ATHLETES_TYPES','ATHLETE_ID','TYPE_ID');
}
secode add this method to TYPE model :
public function athletes()
{
return $this->belongsToMany(ATHLETE::class,'ATHLETES_TYPES','TYPE_ID','ATHLETE_ID');
}
and in last remove ID filed from ATHLETES_TYPES table.
done.
now if you have variable from ATHLETE type with $ATHLETE->types you can get types of than.
read more here :
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
Here are the relationships, buddy
In App/Athlete.php
class Athlete extends Model
{
public function types(){
return $this->belongsToMany('App\Type');
}
}
In App/Type.php
class Type extends Model
{
public function Athletes(){
return $this->belongsToMany('App\Athlete');
}
}

How can i get First table records on base of third table by using laravel 5 eloquent model

Requested tables are listed below:
**User Table**
id, name
1, vehicle person name
2, renter person name
**Vehicle Table**
id, user_id, vehicle_name
1, 1, My car
**Booking Table**
id, renter_id, vehicle_id
1, 2, 1
User Model
public function renter() {
return $this->hasMany(Booking::class, 'renter_id');
}
public function vehicleBook() {
return $this->hasManyThrough(Booking::class, Vehicle::class);
}
Booking Model
public function user() {
return $this->belongsTo(User::class, 'renter_id');
}
Vehicle Model
public function user() {
return $this->belongsTo(User::class);
}
My Controller
$renters = Auth::user()->renter()->get();
$owners = Auth::user()->vehicleBook()->get();
// In Loop
$renter->user->name; // renter person name
$owner->user->name; // vehicle person name
Result
On base of booking Table i want to get renter person and vehicle person name using Laravel 5 ORM.
I have done that using two calls but i want to know if there is any way to get result using one call ?
You could do something like this. It will reduce the number of lines, but will increase the number of queries.
$user = User::find(Auth::user()->id)->with('renters')->with('vehicleBooks')->first();

How build a ternary relationship in Laravel 5

I have three entities:
User
Profile
Status
Summarized, users has a profile foreach status.
EXAMPLE
Users table records
user
id | name
1 user1
2 user2
3 user3
Status table records (this records is previously seeded)
status
id (PK) | title (string)
1 student
2 collaborator
3 teacher
Profile table structure
PROFILE
user_status_id (PK) (FK)
institution (string)
year (timestamp)
user1 is registered as student and fill your profile based on this status. After, he change your status to collaborator and fill another profile referred to this new status.
With that, i want to know:
When user1 was student?
the user1 was already collaborator ever?
Which institution user1 had frequented when he was student?
My first problem is:
How to model this relationship?
I'm not sure but think the above situation is a ternary relatinoship case, right?
And Second problem:
How build using Laravel Eloquent Relationships?
Let's start with relationship
class User extends Eloquent{
protected $table = 'user';
public $timestamps = true;
use SoftDeletingTrait;
public function status(){
return $this->hasOne(Status::class, 'user_id', 'id');
}
public function profile(){
return $this->hasMany(Profile::class,'user_id','id');
}
}
class Status extends Eloquent{
protected $table = 'status';
public $timestamps = true;
use SoftDeletingTrait;
public function user(){
return $this->belongsTo(User::class,'user_id','id');
}
}
class Profile extends Eloquent{
protected $table = 'profile';
public $timestamps = true;
use SoftDeletingTrait;
public function user(){
return $this->belongsTo(User::class,'user_id','id');
}
}
Above relation would somehow will get you what you need but just writing this relation made me question your table structure.
Suggestion DB Change For Better Relation
User
id, username, email, ........
Status
id, status, description, ........
Institutions
id, name, address, ............
User_Status_Institution
user_id,status_id,institution_id,timestamp,.......
This structure allows us that we can have Institution details even if there is no user_profile for that institution. Previous structure you had you can only have institution (name only) detail if and only if there is user profile. Also you can change institution (Name/address/phone etc) at one place and it will update it for all users.
As much as possible try that you can make information to be independent if possible because that reflects in models, object and relations.
Hope it makes sense.

Categories