Laravel 5.2 How to get values from two or more table from a relationship - many-to-many

I have a default authentication table user and another table user_profiles
user(id,email,password)
user_profiles(id,first_name,last_name,mobile)
i am connecting these two table using a many-to-many relationship
for this, i added relationship in the both model class- User and UserProfile
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_profile_id', 'user_id');
}
//UserProfile Model
public function users()
{
return $this->belongsToMany('App\User', 'user_user_profile',
'user_profile_id', 'user_id');
}
and i tried to access the UserProfle details via user table using
$user=\App\User::find(1)->userProfiles()->get();
but not working and also tried
/$user = \App\User::findOrFail(1)->with('userProfiles')->get();
that is also not working , please help to
Get the user_profile table details along with user table
How to access the Pivot table(user_id,user_profile_id) value
How to display these data from multiple tables into a view form?

You have defined the relationship wrong in your User Model: swap user_id and user_profile_id
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_id' , 'user_profile_id');
}

Related

problem with Using pivot table with Eloquent and Laravel

Here is my problem. I have a table called user and table called skills, also I have a pivot table that connects these two called EmployeeSkill. I am trying to fetch the skills that belong to the user but when i use tinker it returns Base table or view not found: 1146 Table 'pfe_sirh_db.skill_user' doesn't exist (SQL: select skills.*, skill_user.user_id as pivot_user_id, skill_user.skill_id as pivot_skill_id, skill_user.employee_id as pivot_employee_id from skills inner join skill_user on skills.id = skill_user.skill_id where skill_user.user_id = 1)' and am using swagger by the way it returns this "withTimestamps": false
class User extends Authenticatable{
protected $table = "users";
public function skills()
{
return $this->belongsToMany(Skill::class);
}
}
and
class Skill extends Model
{
public function User()
{
return $this->belongsToMany(User::class);
}
}
and the pivot table
class EmployeeSkill extends Model
{
protected $table = "employee_skills";
protected $fillable = [
'employee_id', 'skill_id', 'note'
];
}
Your pivot table should be named skill_user (singular) following the model name they belong to. And you don't need a EmployeeSkill model for this relation to work, you only need the table.
As said in the documentation:
to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method
And then you should exclude this line:
protected $table = "employee_skills";
change your table name to skill_user
And in your pivot table you should use user_id as a foreign key
You can retrieve all skills from a user by doing this:
$user = User::find(1);
$user->skills();
This will give you all the skills from the user with the id 1
Be aware that you can use any table name and any foreign key name but if you do that you need to specify the names on the relations. So i recommend you doing what i 've told you, since is the standard way

Laravel eloquent: Save data with relationship

I created an invoice form which has a section where users can dynamically add (via jquery row add) items to be invoiced.
I need to save these data into two tables: Invoice and Invoiceitems. The two tables have one to many via MySQL relationship and Laravel models have hasMany and belongsTo relation assigned.
My question is how to save the data into Invoiceitems table.
In your App\Invoice, define your relationship with App\InvoiceItem as follows:
public function items()
{
return $this->hasMany(InvoiceItem::class);
}
In your App\InvoiceItem model, define your relationship with App\Invoice as follows:
public function invoice()
{
return $this->belongsTo(InvoiceItem::class);
}
To create an Invoice with many InvoiceItem, you would then do something like this:
$invoice->items()->saveMany([
new App\InvoiceItem(['title' => 'iPhone X']),
]);
Read more about Eloquent Relationships.

Laravel 5: User follow another user (like twitter) - how to setup relationship

I have user table .
Relation:
One user can follow more than one user.
How to setup data structure and how to declare relationship in laravel 5.2
Output:
show who are my followers
show my following list ( I follow another user )
create a table followers with these columns: id, user_id, follower_id
2.Create Model like
User Model
public function following(){
return $this->hasMany('App\Follower', 'user_id', 'id');
}
Follower Model
public function following(){
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id');
}

Relationships between tables in laravel using backpack package

I am using backpack CRUD package to create my website project in laravel 5.2
I want to establish a relationship between two tables. First table is called customer and second table is called transaction. Each customer has many transaction(1:N relationship).
Customer table record:
ID Name
123456 xyz
Transaction table record:
ID CustomerID
101010 123456
I know that I have to specify the relation in the customer model. But, how can I display the result of the relationship in CRUD ?
You should have relationships on both the Transaction and the Customer models, so you can do $customer->transactions and $transaction->customer:
class Customer extends Model
{
/**
* Get the comments for the blog post.
*/
public function transactions()
{
return $this->hasMany('App\Transactions', 'CustomerID', 'ID');
}
}
and
class Transaction extends Model
{
/**
* Get the comments for the blog post.
*/
public function customer()
{
return $this->belongsTo('App\Customer', 'CustomerID', 'ID');
}
}
Spend some time in the Eloquent Relationships Documentation. It's really important to understand them if you want to be a Laravel developer.
In order to display the relationship in the CRUD, you can then use Backpack's select column type to display it in the table view and select or select2 field types to display it in the add/edit views. Read the CRUD Example Entity to better understand how that works.
First of all when you are creating migrations for both tables, table which contain Foreign Key (FK) must have field like this:
public function up(){
$table->increments('id');
$table->integer('customerID')->unsigned();
}
After that you are need to call next command into console
php artisan migrate
Next is going next commands:
php arisan backpack:crud customers
php arisan backpack:crud transactions
After that you need to define functions in models which returns values from other tables. Customer models need to have next function
public function transactions(){
return $this->hasMany('Transaction');
}
Transaction model must have next function
public function customer() {
return $this->belongsTo('Customer');
}
Next you must add CRUD field in Customer controller to display
transactions in select box.
$this->crud->addField([
'label' => 'Transactions', // Label for HTML form field
'type' => 'select2', // HTML element which displaying transactions
'name' => 'customerID', // Table column which is FK for Customer table
'entity'=> 'customer', // Function (method) in Customer model which return transactions
'attribute' => 'ID', // Column which user see in select box
'model' => 'Transaction' // Model which contain FK
]);
Hope this helps :)
After you built onetomany relationship with transaction, you can get the results.
$customer=Customer::where(['id'=>'123456'])->with('transaction')
->first();
print_r($customer->Name); // gives the customer name
foreach($customer->transaction as $cid)
{
print_r($cid->CustomerID); // gives the customer id
}
Laravel Relationships Documentation is always helpful. Go through it.

Error in setting up laravel Eloquent relationship

I am trying to set up a relationship in Laravel using the eloquent relationship model, it looks like the one below
users
id
email
projects
id
name
user_projects
user_id
project_id
role
I want to be able to query the projects that the user is a part of irrespective of the role that he has. To do this, I used the following in my user model.
class User extends Model {
public function allProjects() {
return $this->belongsToMany('App\ProjectRoles', 'user_projects', 'user_id', 'project_id');
}
}
But because of this I get an error in my code
Syntax error or access violation: 1066 Not unique table/alias: 'user_projects' (SQL: select `user_projects`.*, `user_projects`.`user_id` as `pivot_user_id`, `user_projects`.`project_id` as `pivot_project_id` from `user_projects` inner join `user_projects` on `user_projects`.`id` = `user_projects`.`project_id` where `user_projects`.`user_id` = 2)
I am not sure how to create the join query in the relationships in order to do it. Any help would be appreciated. I went through the eloquent docs but wasn't able to get the result even though the examples there do exactly what I want.
Your belongsToMany relationship is related to the wrong Model. Generally you don't have a model for your pivot table, but even if you do, your belongsToMany relationship doesn't use it. Your User model should be related to your Project model.
You should use this:
class User extends Model {
public function allProjects() {
return $this->belongsToMany('App\Project', 'user_projects', 'user_id', 'project_id');
}
}