Property [roles] does not exist on this collection instance - laravel

I currently have Accounts Table, Roles Table and AccountRoles Table which store the account id and roleid for the relation. I am trying to get the Role name from the Roles Table by checking the AccountRoles Table for the ID that is tagged to the account ID.
Below is my controller code:
$accounts = Account::with('roles')->where('acc_clinicID', '=', $_SESSION['clinic_ID'])->get();
I tried dd($accounts) and I am able to get the roleName from the relation as attached in the image.
dd($accounts) result
However when I do a dd($accounts->roles->roleName) I got the error: Property [roles] does not exist on this collection instance.
Below is my Model of the tables involved:
Account.php
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
Role.php
public function accounts()
{
return $this->hasMany('App\Models\Account');
}
Please kindly enlightened me on where have I done wrong? Thanks!

#junmingyeo98 Can you please change your relation function in Account.php from belongsToMany to belongsTo.

Related

Check in relationship if a column is true, Laravel

I have 2 tables: roles & users.
In users I have role_id, and I want to check if that role has a column "access_admin_area" on true. If true, I am using a middleware.
Gate::define('admin', function ($user) {
return !empty($user->roles()->where('access_admin_area', true)->first());
});
From User model:
public function roles()
{
return $this->hasOne(Role::class);
}
SQLSTATE[42703]: Undefined column: 7 ERROR: column roles.user_id does not exist↵LINE 1: select * from "roles" where "roles"."user_id" = $1 and "role..
The error describes the issue pretty nicely here - the hasOne relationship method inside your User model expects the Role table row to have a user_id column that specifies a foreign key referencing the user table id column.
If I was you, I'd rather use hasMany relationhip between your User and Role model in this use case, since I expect your users and roles should have a many-to-many relationship
check out the many-to-many relationship eloquent and database structure in the laravel documentation https://laravel.com/docs/7.x/eloquent-relationships#many-to-many
Did you checked like this way:
public function roles()
{
return $this->hasOne('App\Role', 'id' , 'role_id');
}
You should change hasOne to belongsTo
then you can a simpler way to save yourselve from many where clauses in your controlleer is by creating another relationship with eg name as rolewithadminaccess
public function roles()
{
return $this->belongsTo(Role::class);
}
public function rolewithadminaccess()
{
return $this->roles()->where('access_admin_area', true)->limit(1);
}
then you can do this in your controller
return $user->rolewithadminaccess;

Laravel 5.8 Eloquent Model Relationship error

I have a relationship between two models, User and Follower.
User hasMany Follower, and Follower belongsTo User.
In my followers table in the database I have two columns, follower_id and following_id. Both these columns refer to the id column in the users table.
My follower and users table
followers
id
follower_id
following_id
users
id
name
username
User Model
public function followers(){
return $this->hasMany('App\Follower', 'follower_id');
}
public function followings(){
return $this->hasMany('App\Follower', 'following_id');
}
Follower Model
public function user(){
return $this->belongsTo('App\User');
}
In a test controller I am doing this:
$followed = Follower::find(2);
From here, I would like to select one of the columns, follower_id or following_id, and access the user that this particular row belongs to by using $followed->user->name. How would I go about that? Since I need to select a column before accessing, I am a little bit confused.
What can I do to access the data I need?
Your table should be :
followers
id
follower_id
following_id
user_id
users
id
name
username
In your Follower model :
public function user()
{
return $this->hasMany(Follower::class, 'user_id');
}
In your User model :
public function follower()
{
return $this->belongsTo(User::class, 'user_id');
}
Then you can query like this :
$follower = Follower::with('user')->findorFail(2);
$user_name = $follower->user->name;

Get data from pivot table after save in Laravel 5.7

I have two models User and Role
User:
public function roles() {
$this->belongsToMany(Role::class)->withPivot('note');
}
Role:
public function users() {
$this->belongsToMany(User::class);
}
When I add another role to the user:
$role = $user->roles()->save($some_role, ['note' => 'my note']);
I would like to be able to access the pivot id on the role that I just saved like this:
$role->pivot; //null
What am I doing wrong?
You can access elements of a pivot table via the related model.
in your example it would be
echo $user->roles()->find($some_role->id)->pivot('note');
//-> my note
not knowing how your tables are structured I can't help further than inviting you to use php artisan tinker
The pivot is not available on $role because it is not a role object. It should be available on $some_role. Try this:
$some_role->pivot;

Eloquent relationship Laravel 5

I have two models. Article and User. In Article I have this function
public function user()
{
return $this->belongsTo('App\User');
}
in user have this function
public function articles()
{
return $this->hasMany('App\Article');
}
in the git bash after giving php artisan tinker command, when I gave App\Article::first();
it shows the first article of the database.
$user=App\User::first();
this command can show the 1st user.
but when I gave
$user->articles->toArray();
this command it shows that
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to a member function toArray() on null
but as per shown in tutorial, it should show the articles of user 1.
In order to fetch the article, the users table should have a article_id field or the articles table should have a user_id field. Furthermore, the first article you return, try $article->user and check which user is being returned.
The error, you reported is because NO ARTICLE is associated with the given user. In other words, the article doesn't have a user_id set to current user's id.
There are two reasons:
1 aritcles does not have foreign key name user_id referencing user model
2 Since the foreign key is not named as user_id you must explicitly define the foreign key name while defining relationship.
public function user(){
return $this->belongsTo('App\User','foreign_key');
}
public function articles(){
return $this->hasMany('App\Article','foreign_key');
}
Eloquent: Relationships of laravel
1. One To Many
Assume 1 User have many Article
in model of user:
public function user()
{
return $this->hasMany('App\Article','user_id');
}
in model of articles
public function articles()
{
return $this->belongsTo('App\User', 'user_id');
}
Get all articles belong to User
$user = App\User::with('articles')->get();
$articles = $user->articles;
I hope help you!

Laravel BelongsToMany table relation

I have an issue i can't resolve myself with the documentation.
I want to create a very simple conversation system between two users.
I have 3 models and tables:
User
id , name
Conversation
id
Message
id , user_id , conversation_id , content
So a message belongsTo an user and a conversation but then i want the conversation to belongstomany users.
And i dont know how to make this with the tables. If i create a user_id fields in the conversation table i can't have multiple users...
This is definitely in the documentation
Anyways. You're looking for a many to many relationship. For that you need a pivot table (or junction table) that contains the id of a user and the id of a conversation.
Following Laravel convention this table would be called conversation_user and would have the columns id (primary key), conversation_id and user_id
If you have that you can define the relations like this:
User
public function conversations(){
return $this->belongsToMany('Conversation');
}
Conversation
public function users(){
return $this->belongsToMany('User');
}
Querying the relation
$user = User::find(1);
$conversations = $user->conversations;
As documented here for inserting models into a many to many relation you should use attach()
$conversation = new Conversation;
$conversation->users()->attach($idUser1);
$conversation->users()->attach($idUser2);
// or just pass an array of ids
$conversation->users()->attach(array($idUser1, $idUser2));
I would first of all have the three folowig tables:
User
id , name
Conversation_user
user_id , message_id
Message
id , content
Than let's take care of the relationships.
In your User model:
public function conversations()
{
return $this->belongsToMany(Message::class,'conversation_user','user_id','message_id');
}
In your Message model:
public function users()
{
return $this->belongsToMany(User::class,'conversation_user','message_id','user_id');
}
Now you will be able to call the relationship like so:
$user = Auth::user();
$user->conversations();

Resources