John Davidson

php - How to access parent attributes with a relation of belongsTo and hasMany within the same class?

0 comments
Message:


I'm working with Laravel 8, so far I have two models that I want to relate


Role[1]---[n]Users


class Role extends Model
{
use HasFactory;

protected $fillable = [
'name',
];

public function users(): HasMany
{
return $this->hasMany(User::class,'user_id_fk5');
}
}

and the Users looks like this


class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'rol_id',
];

public function role()
{
return $this->belongsTo(Role::class, 'rol_id_fk4');
}

public function hasRole($role): bool
{
Log::info('Checking role ' . $role->role()->first()->get());
Log::info('Current User rolId ' . $this->rol_id);
Log::info('Current User name ' . $this->name);
if ($this->role()->where('id', $role)->first()) {
return true;
}
return false;
}
}

I have read the documentation and it appears that I'm using the correct relationships but I'm not sure how can I query the data from within the same model.


This will result in an exception


$role->role()->first()->get()

I checked this but they query the data from outside of the model and thus not sure how to access the data from the same instance, any clue?


Update


I workarounded the issue with this


public function hasRole(string $roleName): bool
{
$role = Role::where('id', $this->rol_id)->first();
if ($role->name == $roleName) {
return true;
}
return false;
}

at this point, I don't understand what we gain by adding the belongsTo



My Answer:
relationship in the User model if we are not going to use it to directly access the related Role attributes.

If you want to access the Role attributes directly from the User model using the belongsTo relationship, you can modify your hasRole method like this:

php
public function hasRole(string $roleName): bool
{
$role = $this->role;
if ($role && $role->name == $roleName) {
return true;
}
return false;
}


This way, you can access the related Role attributes directly from the User model using the belongsTo relationship.

Rate this post

5 of 5 based on 6953 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us