Getting pivot and reltated tables column values Laravel 3 - php

Good evening peeps, I'm playing a little bit with Laravel, and I have this situation. I have 2 models and 3 tables to display vital signs from a pacient.
Table pacient:
id
names
birthdate
Table vital_sign:
id
description
unit
table pacient_vital_sign
id
pacient_id
vital_sign_id
first_value
second_value
date_time_taken
And the 2 models:
class Pacient extends Eloquent{
public static $timestamps = false;
public function vital_signs(){
return $this->has_many_and_belongs_to('VitalSign', 'pacient_vital_sign', 'pacient_id', 'vital_sign_id');
}
}
class VitalSign extends Eloquent{
public static $timestamps = false;
public static $table = 'vital_signs';
public function pacients(){
return $this->has_many_and_belongs_to('Pacient', 'pacient_vital_sign', 'vital_sign_id', 'pacient_id');
}
}
And for my view I'm sending the pacient whose vital signs I want to display:
$pacient = Pacient::where('active', '=', 1)->first();
So, based on the documentation I could do this to show the pivotal table data:
#foreach($pacient->vital_signs as $sv)
<tr>
<td>{{ $sv->pivot->date_time_taken }}</td>
<td>{{ $sv->description }}</td>
<td>{{ $sv->pivot->first_value }} {{ $sv->pivot->second_value }}</td>
</tr>
#endforeach
But this way, neither the date_time_taken value nor first_value or second_value is showed. Description is displayed.
Now, if I do something like this
#foreach($pacient->vital_signs()->pivot()->get() as $sv)
<tr>
<td>{{ $sv->date_time_taken }}</td>
<td>{{ $sv->description }}</td>
<td>{{ $sv->first_value }} {{ $sv->second_value }}</td>
</tr>
#endforeach
date_time_taken, first_value and secon_value are displayed but I dont know how to reverse the relationship in order to display the value for the related table column, in this case, description from vital_sign table
So I both cases, I'm missing something. Any ideas? What I'm missings?
Thanks

On the Docs:
By default only certain fields from the pivot table will be returned
(the two id fields, and the timestamps). If your pivot table contains
additional columns, you can fetch them too by using the with() method
So in my case, on both models:
return $this->has_many_and_belongs_to('VitalSign', 'pacient_vital_sign', 'pacient_id', 'vital_sign_id')->with('col1', 'col2', 'coln');
and this will work:
#foreach($pacient->vital_signs as $sv)
<tr>
<td>{{ $sv->pivot->date_time_taken }}</td>
<td>{{ $sv->description }}</td>
<td>{{ $sv->pivot->first_value }} {{ $sv->pivot->second_value }}</td>
</tr>
#endforeach

I found this to be useful, but a quick addendum for Laravel 4:
return $this->belongsToMany('Model','pivot_table','this_id','foreign_id')->withPivot('col1','col2');

Related

Attempt to read property "match_name" on null laravel-8

I have
ErrorException
Attempt to read property "match_name" on null (View: C:\xampp\htdocs\Cbangla\resources\views\admin\manage\score\index.blade.php)
Error
I want to fetch all data from my score tables This is my scores table database view
To fetch, all data from the scores table This is what I have in my ScoreController.php
public function index()
{
$data=Score::all();
$team=Team::all();
$match=Matchh::all();
$player=Player::all();
return view('admin.manage.score.index',compact('data','team','match','player'));
}
This is my Score.php model
protected $fillable = ['score_name','score_slug','team_id','match_id','player_id'];
public function team(){
return $this->belongsTo(Team::class);
}
public function matchh(){
return $this->belongsTo(Matchh::class);
}
public function playre(){
return $this->belongsTo(Player::class);
}
This is my index.blade.php
#foreach ($data as $key => $row)
<tr>
<td>{{ $key + 1 }}</td>
<td>{{ $row->score_name }}</td>
<td>{{ $row->score_slug }}</td>
<td>{{ $row->matchh->match_name }}</td>
<td>{{ $row->team->team_name }}</td>
<td>{{ $row->player->player_name }}</td>
</tr>
#endforeach
As I see, there is problem when score has not match or match not found.
First of all, you have to specify relation column, because your model is named Matchh and laravel is looking for matchh_id column.
Solution:
# Score.php model
public function matchh(){
return $this->belongsTo(Matchh::class,'match_id');
}
Tip 1:
You can use optional function, when you're not sure if model has relation or not
#foreach ($data as $key => $row)
<tr>
<td>{{ $key + 1 }}</td>
<td>{{ $row->score_name }}</td>
<td>{{ $row->score_slug }}</td>
<td>{{ optional($row->matchh)->match_name }}</td>
<td>{{ optional($row->team)->team_name }}</td>
<td>{{ optional($row->player)->player_name }}</td>
</tr>
#endforeach
Tip 2:
You can use whereHas function to be sure that Score has Matchh
public function index()
{
$data=Score::query()->whereHas('matchh')->get();
$team=Team::all();
$match=Matchh::all();
$player=Player::all();
return view('admin.manage.score.index',compact('data','team','match','player'));
}
Please add match_id to matchh relationship case the name of your relationship is different than the match id you stored in database
public function matchh(){
return $this->belongsTo(Matchh::class,'match_id');
}
You must provide key in relation because your method name is matchh and in that case relation except matchh_id but in you case it must be match_id.
So:
public function matchh(): BelongsTo
{
return $this->belongsTo(Matchh::class, 'match_id');
}

ErrorException Attempt to read property "name" on null (View:

I have 2 relationships that point to the same User model: operador() and profesional().
class Cita extends Model
{
public function paciente(){
return $this->belongsTo('\App\Models\Paciente');
}
public function profesional(){
return $this->belongsTo('\App\Models\User');
}
public function operador(){
return $this->belongsTo('\App\Models\User');
}
}
In the view I call them like this:
#foreach ($comisiones as $comision)
<tr>
<td>{{ $comision->paciente->name }}</td>
<td>{{ $comision->profesional->name }}</td>
<td>{{ $comision->operador->name }}</td>
<td>{{ number_format($comision->total, 0, '.', '.') }}</td>
<td>{{ $comision->estado }}</td>
</tr>
#endforeach
The program crashes on me when it tries to call $commision->operador->name. If I leave it as a comment it works without problems. But it gives me an error when I have the 2 relations at the same time.
Can I have 2 relationships pointing to the same model? And if not, what alternative do I have? Thanks
For the fact that you are using belongTo relationship, that means User is the parent model and Professional and Operador are the child model.
Hence, it is expected that the table for Professional has a column called user_id, thesame thing for the Operador table, it should have user_id column.
With this the relationship will work just fine.
Yes, you can have 2 relationships pointing to the same model.
When you write :
public function operador(){
return $this->belongsTo('\App\Models\User');
}
Laravel expects that The Migration (The table citas) has a column named operador_id. So Yes you can have multiple relationships to the same model.

belongsTo throwing Trying to get property 'jenis_bahan' of non-object

Model of BahanLab
protected $table = 'bahan_labs';
protected $primaryKey = 'kode_bahan';
protected $fillable = ['kode_bahan', 'nama_bahan', 'kode_sinta', 'kode_jenis', 'harga_bahan', 'stok', 'satuan', 'minimum_stok'];
public $timestamps = false;
public function jenis()
{
return $this->belongsTo('App\JenisBahan', 'kode_jenis');
}
Model of JenisBahan
protected $table = 'jenis_bahans';
protected $primaryKey = 'kode_jenis_bahan';
protected $fillable = ['kode_jenis_bahan', 'jenis_bahan'];
public $timestamps = false;
public function bahans()
{
return $this->hasMany('App\BahanLab');
}
I'm pretty sure that this is correct, I already define the relationship between these tables. But when I tried to do looping echo $bahan->jenis->jenis_bahan, it throws exception.
I already tried some suggestion to do dd($bahan->jenis->jenis_bahan) and I got null, so what is really happening?
UPDATE
Controller:
$bahans = BahanLab::with('jenis')->get();
return view('bahan.daftar-bahan', compact('bahans'));
View:
<tbody>
#foreach($bahans as $bahan)
<tr>
<td>{{ $bahan['kode_bahan'] }}</td>
<td>{{ $bahan['nama_bahan'] }}</td>
<td>{{ $bahan->jenis->jenis_bahan }}</td>
<td>{{ $bahan['harga_bahan'] }}</td>
<td>{{ $bahan['stok'] }} {{ $bahan['satuan'] }}</td>
</tr>
#endforeach
Since you're looping, one of your $bahan objects doesn't have a jenis object (meaning $bahan->jenis is null, so you can't access jenis_bahan of a non-object, of which null is). To handle this, prevent loading $bahans unless it has a jenis, or check for it in the loop:
Controller:
$bahans = BahanLab::has('jenis')->with('jenis')->get();
return view('bahan.daftar-bahan', compact('bahans'));
Or, in your view:
<tbody>
#foreach($bahans as $bahan)
<tr>
<td>{{ $bahan['kode_bahan'] }}</td>
<td>{{ $bahan['nama_bahan'] }}</td>
#if($bahan->jenis)
<td>{{ $bahan->jenis->jenis_bahan }}</td>
#else
<td>No Jenis...</td>
#endif
<td>{{ $bahan['harga_bahan'] }}</td>
<td>{{ $bahan['stok'] }} {{ $bahan['satuan'] }}</td>
</tr>
#endforeach
Note: This #if() check is unnecessary if using ->has('jenis').
Also, you can use ->with() and ->has() together; ->has() restricts the query results to those that have a jenis relationship, ->with() eager loads it to increase performance in large datasets.
It's occured because my table I is a string, not an incremental Integer.
So to solve this problem, I just had to set
public $incrementing = false;

How do I display the name from another model in my view, by the ID in laravel

So i have created 2 models 'Team' & 'Match', 1 controller 'MatchController' and a view 'matches/index.blade.php'.
The Team model has an ID & name.
The Match model has an ID, homeTeam_id & awayTeam_id.
The MatchController has an index method.
The view shows all the matches in de database correctly, but with the homeTeam_id, what I would like is show the name for the teams, from the Team model.
How do i do that? This is what i have now in my view:
#foreach ($matches as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->date }}</td>
<td>{{ $value->homeTeam_id }}</td>
<td>{{ $value->awayTeam_id }}</td>
</tr>
#endforeach
You can create two relationships between Team and Match models:
public function homeTeam()
{
return $this->belongsTo('App\Team', 'homeTeam_id', 'id');
}
public function awayTeam()
{
return $this->belongsTo('App\Team', 'awayTeam_id', 'id');
}
And then load the data:
$matches = Match::with('homeTeam', 'awayTeam')->get();
To display team name do this:
{{ $value->homeTeam->name }}

Laravel Eloquent Relationship Confusion

Here is my situation;
I have an agreements table which will list the different types of agreements there are. It's a lookup table basically.
I have a client_agreements table which list which clients have signed up to which type of agreement. I have an agreement_id within this table (foreign key id).
As I am using Laravel, here is my Controller method to view all agreements for a specific client;
public function index($client_id)
{
$client_agreements = Agreement::find($client_id);
return View::make('client_agreements.index')
->with('client_agreements', $client_agreements);
}
Here is my Agreement Model;
class Agreement extends Eloquent {
protected $table = 'agreements';
public function client_agreements(){
return $this->hasMany('ClientAgreement', 'agreement_id');
}
}
So I want to output in the view from the agreements table;
agreement_type
level
and from the client_agreements table;
start_date
expire_date
My View code (which I'm sure is wrong but don't know why) is essentially;
#foreach($client_agreements as $client_agreement)
<tr>
<td>{{ $client_agreement->agreement_type }}</td>
<td>{{ $client_agreement->level }}</td>
<td>{{ $client_agreement->start_date }}</td>
<td>{{ $client_agreement->expire_date }}</td>
</tr>
#endforeach
What am I doing wrong?
You can do it like this:
$client = Client::with('agreements')->find($client_id);
$client_agreements = $client->agreements;
return View::make('client_agreements.index')
->with('client_agreements', $client_agreements);
And in your view:
#foreach($client_agreements as $client_agreement)
<tr>
<td>{{ $client_agreement->agreement_type }}</td>
<td>{{ $client_agreement->level }}</td>
<td>{{ $client_agreement->pivot->start_date }}</td>
<td>{{ $client_agreement->pivot->expire_date }}</td>
</tr>
#endforeach
This would require the following setup:
Client model
class Client extends Eloquent {
public function agreements(){
return $this->belongsToMany('Agreement', 'client_agreements')->withPivot('id', 'start_date', 'expire_date');
}
}
Agreement model
class Agreement extends Eloquent {
public function clients(){
return $this->belongsToMany('Client', 'client_agreements')->withPivot('id', 'start_date', 'expire_date');
}
}
For more information read the Eloquent docs (especially the section about relationships)

Categories