Laravel 5 insert pivot table with attributes - php

I've been learning laravel for a few days now and I was hoping you guy's could help me.
I have the following table structure:
users
------
id
companies
------
id
company_user
------
company_id
user_id
owner
My User and Company models have functions specified like this:
User Model
public function companies() {
return $this->belongsToMany('App\Company', 'company_user', 'company_id', 'user_id')->withPivot('owner');
}
Company Model
public function users() {
return $this->belongsToMany('App\User', 'company_user', 'company_id', 'user_id')->withPivot('owner');
}
For example when I save a company to a user like this:
User::find(1)->companies()->save(\App\Company::find(1));
The pivot table gets filled nicely, but the owner column doesn't get filled.
I can't find many online how to fill this column. Hope you guys can help me?
Thanks in advance!

You can pass additional data as second argument to save():
User::find(1)->companies()->save(\App\Company::find(1), ['owner' => 'foo']);

Related

How in Laravel make 2 relations to same table?

Having some troubles with relations in Laravel not sure is there any solutions but hope you guys help me.
So let's suppose I have 2 tables USERS and TRAINEES. USERS can be considered as company, admin, instructors depends on field role.
About relations USER as company can have many TRAINEES but also as instructors can have many TRAINEES. So in this case how can I build relations between them? table TRAINEES should have fields COMPANY_ID and INSTRUCTOR_ID ? or how? But it's same table USERS. I don't know if it's clear for you. Just ask me. Count on you guys
Design the users and trainees tables as follows:
users table columns/fields:
id (primary key)
username (string)
role (string, index)
trainees table columns/fields:
id (primary key)
name (string)
trainer_id (integer, index)
company_id (integer, index)
Then in your Trainees model, do this:
public function trainer()
{
return $this->belongsTo('App\User', 'trainer_id');
}
public function company()
{
return $this->belongsTo('App\User', 'company_id');
}
In your User model, do this:
public function trainees()
{
if($this->attributes["role"] == "company")
return $this->companyTrainees();
if($this->attributes["role"] == "instructor")
return $this->instructorTrainees();
return array();
}
public function companyTrainees()
{
return $this->hasMany('App\Trainee', 'trainer_id');
}
public function instructorTrainees()
{
return $this->hasMany('App\Trainee', 'company_id');
}
Use these relationships in your controllers and other places. This is not tested, but it should not be too buggy. Don't forget to seed the database with valid data, especially for the ids.

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

Laravel Relationship through sub table

I'm trying to implement a blog type website where the user can rate the posts. So the relationship is like this:
Blog -> blog_links; To Many fk = blog_id
User -> blog_links; To Many fk = user_id
I've tried these solutions and each time get a different error:
User::hasManyThrough(Blog::class, BlogLink::class);
That didn't work, so I tried query scope:
scopeWithLinksAndResorts($query) {
return $query->with(['resorts' => function($q) {
$q->ordered()->withLinks();
}]);
}
That doesn't seem to return any results. So I'm not sure what I'm doing wrong here. And here's a table example:
blogs
id Title Text
1 Test This is a test blog
users
id email
1 test#test.com
blog_links
id blog_id user_id rating
1 1 1 4
Now from this I want to get the blogs the user has rated and their rating. But as I said I get no results. Anyone able to help?
In your User model define the blog's relation
/**
*
*/
public function blogs()
{
return $this->belongsToMany('App\Blog', 'blog_links', 'user_id', 'blog_id')->withPivot('rating');
}
Then in your Blog model define the user's relation
/**
*
*/
public function users()
{
return $this->belongsToMany('App\User', 'blog_links','blog_id', 'user_id');
}
To get all users with their blogs and rating you can do \App\User::with('blogs')->get()
I'm not sure if this is what you want but hope it helps.

laravel eloquent relationships queries

I have two tables 1)users
{ id, password }
2)expertise { id, expertise}
the relationship I have is
Models
Expertise.php
function User()
{
$this->hasOne('Expertise');
}
User.php
function Expertise()
{
$this->hasOne('User');
}
So how can I query using Eloquent to get the first 10 users with a certain expertise?
I want to join users.id = expertise.id and get the first 10 people with a specified expertise (Where clause).
Beginner to laravel, I've checked other sources but was not successful
Right now you are having a problem with the way that you modeled your data. If you have a one-to-one relationship the best practice to model it is to have one entity store the id of the other. The Laravel convention for this is to have a column named <model>_id:
Users
| id | password |
Expertises
| id | expertise | user_id |
Then in your models you can do this:
Models
Expertise.php
class Expertise extends Eloquent
{
public function User()
{
// because expertise has a column user_id
// expertise belongs to user
return $this->belongsTo('User');
}
}
User.php
class User extends Eloquent
{
public function Expertise()
{
// because expertise is the one with the column
// user_id, user has one expertise
return $this->hasOne('Expertise');
}
}
The Query
After you have all this set up, to be able to query the first 10 users with a certain expertise you can do this.
$users = User::whereHas('Expertise', function($q)
{
$q->where('expertise', '=', <expertise you are looking for>)
})
->take(10)
->get();
To get a further reading in querying relationships in Laravel please take a look at this:
Laravel - Querying Relationships
Keep in mind
keep in mind that the tables name must be plural, if not then you should specify the name of the table inside the model:
protected $table = 'expertise';

Adding a HABTM as a registration in CakePHP

I have Users and Courses.
I have a users table, and a courses table.
I also have a course_memberships table with id |
course_id | user_id
I have the appropriate hasmany relationship
for courses and users to relate to CourseMembership
But I have no idea how to create that relationship using a button on the front end. Something like a public function register() on the Courses controller that would put the Auth User ID in the user_id field, and the course id in the course_id field to form the relationship.
I know it was a wall of text, but I figured a description of the issue may be more helpful than an endless scroll of code.
Can anyone help?
You should create a method to save to the CourseMembership model within the Courses Controller. Something like this would work.
public function register($course_id){
$user_id = $this->Auth->user('id');
$data = array(
course_id => $course_id,
user_id => $user_id;
);
if($this->Courses->CourseMembership->save($data)){
$this->Session->setFlash('Registered');
$this->redirect($this->referer());
}
else{
$this->Session->setFlash('Could not register');
$this->redirect($this->referer());
}
}
This way, when people go to /Courses/register/1, it would register them for the course with the ID of 1.
Then when you do a find on the User, the data would be in $user['CourseMembership']

Categories