BelongsTo relation Laravel 5.4 not working - php

I have two models (see below). With a one to many relationship, the HasMany relationship is working as expected, but the inverse belongsTo doesn't get any results when I try to do this.
$user = Auth::user();
dd($user->location->name);
I have the following database structure
Table locations
id
name
slug
Table users
id
name
email
password
location_id
remember_token
App/User model
public function location() {
return $this->belongsTo( 'App\Models\Location' );
}
and the App\Models\Location model
public function users()
{
return $this->hasMany('App\User');
}

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

How to order by many-to-many relationship Laravel Eloquent

I have many-to-many relationship users|pivot|task
I need to order records by pivot table column(role) and by user table column(name). Ordering by pivot works, but order by users doesnt. Please give any advice how to fix this
Job model
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class,'user_job')
->using(UserJob::class)
->withPivot('role')
->withTimestamps();
}
User Model
public function jobs(): BelongsToMany
{
return $this->belongsToMany(Job::class,'user_job')
->using(UserJob::class)
->withPivot('role')
->withTimestamps();
}
Repository
return User::find($dto->getUserId())
->jobs()
->where($dto->getFilters())
->with('users')
->orderBy($dto->getSortBy(),$dto->getSortType()) // need to order by users.name
->paginate($dto->getPerPage());

Laravel hasManyThrough 2 tables

i have two tables as below:
users table:
|id|name|email|password|created_at|updated_at
messages table:
|id|sender_id|receiver_id|message|created_at|updated_at
User model:
public function threads()
{
return $this->hasManyThrough(Message::class, User::class,'id','sender_id');
}
i'm trying retrieve message threads
which isn't working. any help appreciated.
This is an example from laravel eloquent relationship
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
can you review your code
It seems that you want to retrieve all messages that belongs to a single thread (list of users) using hasMany relationship Through User model, to do that You have to define hasManyThrough inside Thread model not in User model, here is an example:
User:
|id|name|email|password|created_at|updated_at|thread_id
Note thread_id foreign key because thread is a list of users
Thread:
class Thread extends Model {
public function messages() {
return $this->hasManyThrough(Message::class, User::class,'thread_id','sender_id', 'id', 'id');
}
}
Example from laravel doc

Laravel foreign key relation

I've got a strange problem.
I've a users table and a company table. A User belongsTo a company and a company hasMany users.
Both primary keys of the table are id.
In the laravel documentation I read the following:
Additionally, Eloquent assumes that the foreign key should have a
value matching the id column of the parent.
I've got this in my CompanyModel:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class);
}
When I try this:
$users = CompanyModel::find(1)->users;
dd($users);
It's not working. When I add a foreign key in my relation it works!?:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class, 'id');
}
This is strange right? What on earth am I doing wrong.
--EDIT--
In my users table I've got a company_id column!
Firstly, I would suggest you rename your Model from CompanyModelto Company and from UserModel to User.
Then ensure you have company_id in your users table. And in your users migration file connect the users table with the companies table as such:
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
Don't forget to refresh your database.
Then in your models, define the relationships as such:
// User model
// Laravel will automatically identify and use the `company_id` field in your reference
public function company(){
return $this->belongsTo(Company::class);
}
// Company model
public function users(){
return $this->hasMany(User::class);
}
You can then fetch your records in your controller as such:
$user = User::find(1);
$user_company = $user->company; // This might not be necessary in your controller, you can do it in your view
dd($users, $user_company);

Laravel Eloquent Relationship custom query

I have 2 tables: USERS and SUBJECTS
The relationship between USER and SUBJECT is many to many.
In the User.php and Subject.php models, I defined:
User.php
function subjects() { return $this->belongsToMany('App\User'); }
Subject.php
function users() { return $this->belongsToMany('App\Subject'); }
The pivot table is subject_user and it has 3 columns:
subject_id, user_id, finished
The finished value can only be between 0 and 1.
Now I know that when I want to select all the subjects that an user studied, I have to write $user->subjects.
But what if I want to select all the subjects that an user studied and the finished value in the pivot table is equal to 1?
You need to add "withPivot()" to your relationship definitions, like this:
function subjects() { return $this->belongsToMany('App\User')->withPivot('finished'); }
function users() { return $this->belongsToMany('App\Subject')->withPivot('finished'); }
Then you can do:
$user->subjects()->where('finished', 1)->get();
You will need to eager load that relationship and use the wherePivot method.
$user = User::with(['subjects' => function($q) {
$q->wherePivot('finished', 1);
}])->fine($user_id);

Categories