Get data from pivot table after save in Laravel 5.7 - laravel-5

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;

Related

Property [roles] does not exist on this collection instance

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.

Login using passport with password in related table laravel 6

I'm using Vue for frontend and Laravel as a backend services.
In my case I have two tables contacts and contact_has_entities tables.
My contacts table is :
contact_id name email
And contact_has_entities table is :
id_contact_has_entity contact_idcontact password
contact_idcontact is a foreign key for the contacts table.
I'm using passport package for authentication. When login request comes then I need to check email from contacts table and password from contact_has_entities table.
I used the below function
public function getAuthPassword() {
return ContactHasEntity::where('password', $this->password)->first();
}
In my Contact model i have defined relationship like below :
public function entity() {
return $this->hasOne('App\Models\ContactHasEntity', 'contact_idcontact', 'contact_id');
}
But I'm getting error like
getAuthPassword does not exist
Is there any way to achieve this or is it not possible with Passport?
With the above relationship defined then below should work:
Access the contacts model and query through the relationship the entities model as shown below:
Contacts::whereHas('entity', function ($query) {
return $query->where('password', $this->password);
})->first()`;
Or under contacts define a query scope:
public function scopeAuthPassword($query, $password)
{
return $query->entity()->where('password', $password);
}
//which would translate to this when:
Contacts::authPassword($request->password)->first()
Below function in my Contact model did the work :
public function getPasswordAttribute() {
return $this->entity->getAttribute('password');
}
Here i added the function to use password field from ContactHasEntity model.

How get users from section table ? laravel

The idea is that I have relation between two table's section and user
the section_id exist in users table it relation with id section
SO for ex : section_id = 2 > want to bring all users belongs to id section
My code here use id from url and I don't want to do this I want without id bring all users :
public function getAllUsers($id)
{
$data = User::where('section_id',$id)->get();
}
If I'm understanding you correctly, you want to get all the users for a particular Section that have the relationship to that section.
Assuming you have the relationship set up correctly on the Section model:
public function users() {
return $this->hasMany('App\User');
}
I suggest you go about this 'backward' and just pull the users from the Section model itself (eager loading allows one query):
$section = Section::with('users')->first();
$usersForThisSection = $section->users;
If you setup a One to Many relationship you can say things like: $user->section to return the section a user belongs to...and $section->users to get a collection of all the users in a section -- the getAllUsers() is redundant in this case.
Make sure your User and Section models contain these methods. Sounds like your migration was setup properly if you have a section_id column on your users table.
More info on one-to-many here: https://laravel.com/docs/5.8/eloquent-relationships#one-to-many
// app/User.php
class User extends Model
{
public function section() {
return $this->belongsTo('App\Section');
}
}
// app/Section.php
class Section extends Model
{
public function users() {
return $this->hasMany('App\User');
}
}
Test out your relationships in php artisan tinker like so...
$user = User::find(1);
$user->section
$section = Section::find(1);
$section->users
you need a unique identifier to receive section_id's users. receive it from url(get) or ajax(post) . if you worry about users access then use "auth"

Polymorphic relations in Laravel

Please, Help me!
I have User model and migration: id, login, password.
3 roles and models (Admin, Teacher, Student) and here more information about user. And user can get several roles (he can be admin and teacher)
And one polymorphic model Role with columns:
user_id
roleable_id
roleable_type
For example, User::find(1)->roles;
And i'd like that result shows two model (admin and teacher).
Pleasee, help me))
You could try to eager load the models by using this in your User model https://gist.github.com/thisdotvoid/3022fee8afa53e45a6b89da3f16b3815. Add the required morph functions and then add three functions to the user model similar to this one (change the name and the model name accordingly):
public function admin()
{
return BelongsToMorph::build($this, 'App\Admin', 'rolable');
}
Then create a mutator function like
function getRolesAttribute()
{
$roles = new Collection();
$roleNames = ['admin', 'teacher', 'student'];
foreach ($roleNames as $role) {
$hasRole = $this->{$role};
if ($hasRole) {
$roles->push($role);
}
}
return $roles;
}

Expand sentry users table

I expanded Sentry users table with few columns, but in this case I need help for city_id column. I did it in Laravel migrations. Now I need to make relationship between Sentry users and cities table.
I try to expand Sentry user Model and add belongsTo, but I cannot use it from Sentry::findUserById() like Sentry::findUserById()->with('city')
How can I expand Sentry user model with relationship to another table/model?
class User extends Eloquent {
public function city() {
return $this->hasOne('City', 'id', 'city_id');
}
}
Then you should be able to do something like this in your controller
$city = User::find($id)->city->name;
Or in your view you can do
{{ $user->city->name }}

Resources