Struggling with Laravel's morphable relationships - laravel

In a project, let's say that we have Customers, and each customer can have one Voucher. The voucher, though, may be for a different thing for different customers - maybe for a Hote, a Car or a Flight.
We have a table of flight voucher codes, a table of hotel voucher codes and a table of car voucher codes.
When a customer is allocated a voucher, therefore, we allocated them the next code for the relevant thing that they're getting a voucher for. But rather than have multiple tables (customer_car_voucher, customer_hotel_voucher, and so on) I would rather have a Voucher table which is, in turn, linked to the relevant voucher type.
What I want to be able to do is just go $customer->voucher->code to get the relevant code, whether that be a flight, a hotel or a car. Other vouchers may be added at a later date, you see, for different things.
I think I can do this using morphable relationships - the voucher morphsTo car, hotel and flight, so within the the voucher table there is a "voucherable_type" and a "voucherable_id". But damned if I can get it to work.
Any help, please? Am I going about it wrong?

you arte right. and for a hint use:
public function customer()
{
return $this->belongsTo(Customer::class):
}
public function voucherable()
{
return $this->morphTo();
}
in voucher model.
and for each flight,car,hotel include:
public function voucher(){
return $this->morphOne(Voucher::class,'voucherable');
}
you can see Laravel morph relationship too for more help.

In Laravel's Eloquent ORM is used for morphable relationships.
First, create two Models AirVoucher and Voucher.
First, the AirVoucher model uses the following relationship.
public function voucher()
{
return $this->morphOne(Voucher::class, 'voucherable');
}
Second, the Voucher model uses the following relationship.
public function voucherable()
{
return $this->morphTo();
}
You can use the following Laravel official relationship document for more help.
Laravel Morph Relationships.

you must use laravel Polymorphic Relationships.
in Voucher model set this model as polymorph model(function name = modelname+"able"):
public function voucherable() \Illuminate\Database\Eloquent\Relations\MorphTo
{
return $this->morphTo();
}
then in Car model (or hotel/fight) set realation(function name= polymorph name):
if each car has one voucher, use morphOne:
public function files(): \Illuminate\Database\Eloquent\Relations\MorphOne
{
return $this->morphOne(Voucher::class, 'voucherable');
}
if each car has many voucher, use morphMany:
public function files(): \Illuminate\Database\Eloquent\Relations\MorphMany
{
return $this->morphMany(Voucher::class, 'voucherable');
}
Retrieving The Relationship
$car = Car::find(1);
$vocher = $car->voucher;
laravel docs

Related

hasOneThrough relationship Laravel

A contract has a representative (which is a user).
Currently I get this relationship with an belongsTo directly like this in my Contract model:
class Contract extends Model
{
public function representative()
{
return $this->belongsTo(User::class);
}
I would like to be able to retrieve this relationship through the organization_user table and retrieve the "position" attribute.
I think I should use the hasOneThrough relationship but I can't get what I'm looking for.
class Contract extends Model
{
public function representative()
{
return $this->hasOneThrough(User::class, OrganizationUser::class);
}
Not sure if you're in a position to change your DB structure, but it seems to me that your table contracts and organization_user are duplicating each other, storing the same data.
Would it make sense to leave only one table organization_user as a pivot table with the position?
Then you wouldn't need to make the big loop over few relationship to get the needed data.

Laravel: Load only pivot additional columns without relation

I have the following structure:
Charge
id
amount
created_at
..
Payment
id
amount
created_at
..
and a pivot table charge_payment, since one charge can be covered partially by multiple payments.
charge_payment
charge_id
payment_id
amount
The amount column on the pivot table defines the amount that the given Payment covers for the Charge.
And I need to get only the "paid" amount for a Payment.
I have the following models:
// Charge.php
class Charge extends Model
{
public function payments()
{
return $this->belongsToMany('App\Payment')->withPivot('amount');
}
}
// Payment.php
class Payment extends Model
{
public function charges()
{
return $this->belongsToMany('App\Charge')->withPivot('amount');
}
}
I want to be able to get only the paid amount with:
$payment = Payment::find(..);
$paid_amount = $payment->charges->sum('pivot.amount');
However, with this approach the related models are loaded from the database and I won't be needing them.
Is there a way to load only the additional pivot column without the related models?
Thank you very much!
Firstly, if one Payment can be always related only to one Charge, I would advise you to change the relationship from many-to-many to one-to-many (it will be just more correct and simpler).
Than you can simple use aggregate function (in your case withSum) which will return you only resulting values without relationship Models.
$payment = Payment::withSum('payments', 'amount')->find(..);
{{ $payment->payments_sum_amount }}

Laravel Belongs to many relationship response Error

I'm working on my school Laravel Project. I have four models User,Klass,course and School
these are My Relations
User Model//
public function teacherCourses(){
return $this->belongsToMany(Course::class,'course_teachers','teacher_id','course_id');
}
public function klasses(){
return $this->belongsToMany(Klass::class,'course_teachers','teacher_id','klass_id');
}
and
klass model//
public function teacherCourses(){
return $this->belongsToMany(Course::class,'course_teachers','klass_id','course_id');
}
and
Course Model//
public function klasses(){
return $this->belongsToMany(Klass::class,'course_teachers','course_id','klass_id');
}
My course_teachers table have course_id,teacher_id(user),klass_id,and school_id.
I want to return A teacher with his klasses and assigned courses inside the class.. how can i get that
i have tried
$user=User::with('klasses.teacherCourses')->where('id',$teacher->id)->first();
But I am getting the response with some extra data.. like the it also return other courses with having same classId (the course which is not assigned to the user).
how can i change this
is my relations are correct??
note: teachers can be assigned many classes and courses .. every relation is many to many i think
Can you retrieve klasses and teacherCourses separately?
$user = User::with(['klasses', 'teacherCourses'])
->find($teacher->id);
or
$teacher->load('klasses', 'teacherCourses');
This way, additional klasses and courses will be associated with only one teacher, but you lost the relation between klasses and courses.

Laravel - Eloquent relation whereHas one or more other relations

I'm learning Laravel and Laravel eloquent at the moment and now I try to solve a problem using relations in Laravel.
This is what I want to archive:
The database holds many sport clubs. A sport club has a lot of teams. Each team has games. The teams table has a column named club_id. Now I want to create Eloquent relations to get all games of a club.
Here is what I got so far:
Club model
id => PRIMARY
public function games()
{
return $this->hasMany('App\Models\Games')->whereHas('homeTeam')->orWhereHas('guestTeam');
}
Game model
home_id => FOREIGN KEY of team ; guest_id => FOREIGN KEY of team
public function homeTeam()
{
return $this->belongsTo('App\Models\Team','home_id')->where('club_id','=', $club_id);
}
public function guestTeam()
{
return $this->belongsTo('App\Models\Team','guest_id')->where('club_id','=', $club_id);
}
Team model
id => PRIMARY ; club_id => FOREIGN
In my controller all I want to do is Club::findOrFail($id)->games()
Executing the code above returns a SQL error that the games table does not have a column named club_id.
What is the correct way to create this kind of relation?
Thanks!
EDIT
Thanks to Nikola Gavric I've found a way to get all Games - but only where club teams are the home or away team.
Here is the relation:
public function games()
{
return $this->hasManyThrough('App\Models\Game','App\Models\Team','club_id','home_id');
}
How is it possible to get the games where the home_id OR the guest_id matches a team of the club? The last parameter in this function does not allow an array.
There is method to retrieve a "distant relationship with an intermediary" and it is called Has Many Through.
There is also a concrete example on how to use it which includes Post, Country and User, but I think it will be sufficient to give you a hint on how to create games relationship inside of a Club model. Here is a link, but when you open it, search for hasManyThrough keyword and you will see an example.
P.S: With right keys naming you could achieve it with:
public function games()
{
return $this->hasManyThrough('App\Models\Games', 'App\Models\Teams');
}
EDIT #01
Since you have 2 types of teams, you can create 2 different relationships where each relationship will get you one of the type you need. Like this:
public function gamesAsHome()
{
return $this
->hasManyThrough('App\Models\Games', 'App\Models\Teams', 'club_id', 'home_id');
}
public function gamesAsGuests()
{
return $this
->hasManyThrough('App\Models\Games', 'App\Models\Teams', 'club_id', 'guest_id');
}
EDIT #02
Merging Relationships: To merge these 2 relationships, you can use merge() method on the Collection instance, what it will do is, it will append all the records from second collection into the first one.
$gamesHome = $model->gamesAsHome;
$gamesGuests = $model->gamesAsGuests;
$games = $gamesHome->merge($gamesGuests);
return $games->unique()->all();
Thanks to #HCK for pointing out that you might have duplicates after the merge and that unique() is required to get the unique games after the merge.
EDIT #03
sortBy also offers a callable instead of a attribute name in cases where Collection contains numerical indexing. You can sort your Collection like this:
$merged->sortBy(function($game, $key) {
return $game->created_at;
});
When you define that Club hasMany games you are indicating that game has a foreign key called club_id pointing to Club. belongsTo is the same but in the other way. These need to be coherent with what you have on your database, that means that you need to have defined those keys as foreign keys on your tables.
Try this...
Club model
public function games()
{
return $this->hasMany('App\Models\Games');
}
Game model
public function homeTeam()
{
return $this->belongsTo('App\Models\Team','home_id');
}
public function guestTeam()
{
return $this->belongsTo('App\Models\Team','guest_id');
}
Your Query like
Club::where('id',$id)->has('games.guestTeam')->get();

how to load foreign relationship laravel 5

I am storing information on a 4-day class. The information is dates 1-4 and each date has an instructor associated with it as there can be different instructors on different days. Let's just talk about day_1 and instructor_day_1 for now. My models are as follows:
Course Model:
public function instructor()
{
return $this->belongsTo('App\Instructor');
}
Instructor Model:
public function course()
{
return $this->hasMany('App\Course');
}
When i go to the #show method in my controller, i find the correct course but when i try to load the view, i can't figure out how to access the foreign relation. Right now i'm trying:
<p class="card-text">{{$course->day_1}} assigned to {{$course->instructor_day_1->instructor->name}}</p>
But that's not yielding anything but errors. If i do {{$course->instructor_day_1}}, i get the correct value from the database.
Is my relationship backwards? Does Course model need be "belongsToMany"? What is the correct syntax for pulling the instructor info? Do i need to specify any foreign key relations in my models?
belongsTo is the correct relationship, but it's not set up correctly. And you'll need 4 of them, 1 for each foreign key on the courses table.
This should get you started:
public function instructorDay1()
{
return $this->belongsTo('App\Instructor', 'instructor_day_1');
}
And then you would call it like this, to get instructor's name:
$course->instructorDay1->name;
And you'll need to do this for all 4 relationships.

Resources