Laravel many to many relationship with pivot - laravel

I'm using Laravel Filament.
I got a projects and responsibles tables in a many-to-many relationship. But also another table of responsabilityTypes
projects
id
title
responsibles
id
name
responsabilityTypes
id
name
project_responsible
project_id
responsible_id
responsibilityType_id
And here are my relationships setup:
Responsible.php
public function projects() {
return $this->belongsToMany(Project::class,'rel_project_responsible','responsible_id','project_id')
->withPivot('responsibilityType_id')
->withTimestamps()
->using(AcademicoProyecto::class);
}
Project.php
public function responsibles() {
return $this->belongsToMany(Responsible::class,'rel_project_responsible','project_id','responsible_id')
->withPivot('responsibilityType_id','sort')
->withTimestamps()
->using(AcademicoProyecto::class);
}
I have set up a class for the pivot table like so:
ProjectResponsible.php
use Illuminate\Database\Eloquent\Relations\Pivot;
class AcademicoProyecto extends Pivot
{
}
ResponsibilityType.php
//Don't know how to set up
My question is, when the user is in a Project Edit page and clicks on the "attach" button, in order to add a Responsible record, a Modal pops up to select a Responsible, but I also implemented a Select list to display the different types of responsibilities.
What am I missing to set up in order to access and display the types of responsibilities in the select list and attach it to the pivot table?

Your question asks about "access and display" but you have no controller or view code. But for the model, it's just a simple relationship between two tables, so define it as such:
class AcademicoProyecto extends Pivot
{
use SoftDeletes;
public function responsibilityType() {
return $this->belongsTo(ResponsibilityType::class);
}
}
class ResponsibilityType extends Model
{
protected $fillable = ["name"];
}
Now you simply update the other models to access the relationship in the withPivot() call.
class Responsible extends Model {
public function projects() {
return $this->belongsToMany(Project::class,'rel_project_responsible','responsible_id','project_id')
->withPivot('responsibilityType')
->withTimestamps()
->using(AcademicoProyecto::class);
}
}
class Project extends Model {
public function responsibles() {
return $this->belongsToMany(Responsible::class,'rel_project_responsible','project_id','responsible_id')
->withPivot('responsibilityType', 'sort')
->withTimestamps()
->using(AcademicoProyecto::class);
}
}
Now you should be able to do, for example:
$foo = Responsible::with("projects")->first();
foreach ($foo->projects as $project) {
echo $project->pivot->responsibilityType?->name;
}

Related

How to add additional column relationship in pivot table in Laravel

Version: Laravel 5.4
I have 3 Models
Model: Employee
protected $fillable = ['name'];
public function emails(){
return $this->belongsToMany('App\Email')->using('App\EmailEmployee');
}
Model: Email
protected $fillable = ['username'];
public function employees(){
return $this->belongsToMany('App\Employee')->using('App\EmailEmployee');
}
Every Employee has many email access and emails allocates to many employees. But I have another column in email_employee table
email_id (emails table)
employee_id (employees table)
assigned_by (employees table)
how to make relation of assigned_by column with employees table
Pivot Model
use \Illuminate\Database\Eloquent\Relations\Pivot;
class EmailEmployee extends Pivot{
public function assignedBy(){
return $this->belongsTo('App\Employee');
}
}
I tried
$email = Email::find(1);
dd($email->employee[0]->pivot->assignedBy);
But not working
Custom Intermediate Table Model
To solve your problem, you should look to use the ->using() method on the belongsToMany method.
The subsection "Defining Custom Intermediate Table Models" in this link briefly describes this. eloquent-relationships#many-to-many
You basically create a model for the pivot table so that you can define additional relations to it.
You can still access data from Blade and Controllers the way you are now as Laravel will still deal with the relationship for you. However, you can access the pivot table with ->pivot and as you have told laravel to use a model for the pivot table, you can also access all the relationship defined functions from that model.
Example:
Employee
class Employee extends Model
{
protected $fillable = ['name'];
public function emails(){
return $this->belongsToMany('App\Email')
->using('App\PivotModel');
}
}
Email
class Email extends Model
{
protected $fillable = ['username'];
public function employees(){
return $this->belongsToMany('App\Employee')
->using('App\PivotModel');
}
}
PivotModel
class EmailEmployee extends Pivot
{
public function assignedBy(){
return $this->belongsTo('App\Employee','assigned_by');
}
}
Be Sure to extend Pivot on the pivot model and not Model
Now you can just do:
$user->emails()->first()->pivot->assignedBy
The reason for the ->first() is that you have a many to many, meaning that you will be getting a collection of emails assigned to the user. You would normally loop through them but for this example, simply selecting the first will do the same.
If you just want the column value and not the relationship value, then add ->withPivot('assigned_by') which will allow you to access the value directly.
If you are wanting to audit when the assignment was made, then you may also want to add ->withTimestamps() if your pivot table has timestamps included, so that you can access those too.
Changes in Pivot model
Pivot Model
use \Illuminate\Database\Eloquent\Relations\Pivot;
class EmailEmployee extends Pivot{
public function assignedBy(){
return $this->belongsTo('App\Employee','assigned_by');
}
}
You can use an custom pivot model
EmailEmployee
class EmailEmployee extends Pivot
{
public function giver()
{
return $this->belongsTo('App\Employee');
}
}
Employee
class Employee extends Model
{
public function emails(){
return $this->belongsToMany('App\Email')->using('App\EmailEmployee');
}
}
Email
class Email extends Model
{
public function employees()
{
return $this->belongsToMany('App\Employee')->using('App\EmailEmployee');
}
}
So you can access giver by $email->pivot->giver;

How can I get all records belonging to the model class as relation on a 1-M polymorphic relation

I am trying to store statuses of multiple models in a polymorphic relationship and use them from there.
The retrieving of the status works but besides that I need to get all (available) the statuses belonging to that specific model. And then eager load them so I can use them in a select form or somewhere else.
Here is a representation:
// Status.php
class Status extends Model
{
public function statusable()
{
return $this->morphTo();
}
}
// Article.php
class Article extends Model
{
public function status()
{
return $this->morphOne(Status::class, 'statusable', 'statusable_type', 'statusable_id', 'status');
}
}
// Post.php
class Post extends Model
{
public function status()
{
return $this->morphOne(Status::class, 'statusable', 'statusable_type', 'statusable_id', 'status');
}
}
Here I can get the status(details) of the selected model like App\Article::first()->status()->get() or eager load it as expected. What I want is to add a method where I can call (all) statuses that belong to that particular model. For example:
$article = App\Article::first()->statuses();
and then return all available statuses to this model. I can (did) of course create a method like:
// Article.php
...
public function statuses()
{
$statuses = Status::where('statusable_type', self::class)->get();
return $statuses;
}
But this way I cant eager load it because I don't return a relationship. So is there a cleaner way where I can use eager loading as well?

Laravel | Using Eloquent hasManyThrough

I have a table called invoiceDetails that has item_id as foreign key from another table called items which has category_id as foreign key from table called categories.
I want to do that following using eloquent:
$result = InvoiceDetail::groupBy('item_id')
->selectRaw('sum(qty) as qty, item_id')->with('item', 'category')->get();
but I am getting error:
Call to undefined relationship [category] on model [App\InvoiceDetail].
Here's my relation inside Category model:
public function invoiceDetail() {
return $this->hasManyThrough('App\InvoiceDetail', 'App\Item', 'category_id', 'item_id');
}
Any suggestions?
Not sure you would even need a hasManyThrough relation here, unless you want to fetch all InvoiceDatail objects belonging to all items which in turn belong to the Category. That part is not clear from your question.
But in your example you are fetching items with their category from distinct item_id.
The reason this is not working is because you are trying to fetch the category relation from the InvoiceDetail object, which does not exist.
->with('item', 'category')
You want to load the Category based on the item relation, not based on the InvoiceDetail, try the dot notation (given that you did define the other relations)
->with('item.category')
Relations should be like this:
class InvoiceDetail extends Model
{
public function item()
{
return $this->belongsTo(\App\Item::class);
}
}
class Item extends Model
{
public function invoiceDetails()
{
return $this->hasMany(\App\InvoiceDetail::class);
}
public function category()
{
return $this->belongsTo(\App\Category::class);
}
}
class Category extends Model
{
public function items()
{
return $this->hasMany(\App\Item::class);
}
public function invoiceDetails()
{
return $this->hasManyThrough(\App\InvoiceDetail::class, \App\Item::class, 'category_id', 'item_id');
}
}
You would want to use the hasManyThrough if, for example, you have a Category and you want to load all the InvoiceDetails directly.
dd($category->invoiceDetails);

Laravel query multiple tables using eloquent

hi sorry bit of a newbie here but I am have three tables users, profiles, friends. they all have the user_id fields within them and I want fetch all of the fields in one statement using Eloquent and not DB::statement and doing the table joins.
How can I achieve this?
Try this
use the User class and the with method that laravel has to query model relationships
$user = User::with(['profile', 'friend'])->get();
Ensure your models has the correct relationships as follows:
app/models/User.php
public function friend () {
return $this->hasMany('Friend');
}
public function profile () {
return $this->hasOne('Profile');
}
app/models/Profile.php
public function user() {
return $this->belongsTo('User');
}
app/models/Friend.php
public function user() {
return $this->belongsTo('User');
}
use some thing like this:
You should define relations in your models with hasOne, hasMany.
class Review extends Eloquent {
public function relatedGallery()
{
$this->hasOne('Gallery', 'foreign_id', 'local_id');
}
}
class Gallery extends Eloquent {
public function relatedReviews()
{
$this->hasMany('Review', 'foreign_id', 'local_id');
}
}
$gallery = Gallery::with('relatedReviews')->find($id);
Will bring the object Gallery with
$gallery->id
gallery->name
...
$gallery->relatedReviews // array containing the related Review Objects

Many to Many with additional table in L4

I have a schema like that:
And now I want to use it in Laravel 4. So far, I could only achieve getting games for certain user, without touching owntype. Code:
public function games() {
return $this->belongsToMany('Game','games_users','owntype_id','games_id')->where('user_id','1');
}
The only thing I'm getting is onwtype_id. How can I add owntype table to the "equasion"?
You can access extra pivot table columns by specifying them through the withPivot function on the relationship function.
Basically I think you want to do this:
class User extends Eloquent {
public function games()
{
return $this->belongsToMany('Game', 'games_users')->withPivot('owntype_id');
}
}
class Game extends Eloquent {
public function users()
{
return $this->belongsToMany('User', 'games_users')->withPivot('owntype_id');
}
}
class Owntype extends Eloquent {
protected $table = 'owntype';
}
// Now you can do:
foreach ($user->games as $game)
{
// Echo each Owntype description.
echo Owntype::find($game->pivot->owntype_id)->description;
}
For the record... I think you might be taking it too far by creating a new table for owntype. Just set the description as a type column on the pivot table. Also make sure that your pivot table is named game_user (singular, alphabetically) and Laravel will know which pivot table to use automatically.
class User extends Eloquent {
public function games()
{
return $this->belongsToMany('Game')->withPivot('type');
}
}
class Game extends Eloquent {
public function users()
{
return $this->belongsToMany('User')->withPivot('type');
}
}
// Now you can do:
foreach ($user->games as $game)
{
// Echo each ownership type.
echo $game->pivot->type;
}
Some more info about working with pivot tables can be founded in the Laravel 4 docs.

Resources