I’m new to laravel relations and eloquent and I have the following three models and I want to get the num_rooms by using a reservation object inside my blade view which , I tried the below code but it didn’t work and I got an error :
“Trying to get property ‘rtypes’ of non-object”
how can I achieve this ?? and thank you in advance
@foreach($reservations as $reservation)
<p>{{$reservation->rdates->first()->rtypes->first()->num_rooms}}</p><br>
@endforeach
Reservation model:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Reservation extends Model
{
protected $table = 'reservations';
protected $dates = [
'canceled_at'
];
protected $fillable = [
'canceled_at',
'created_by',
'updated_by'
];
public function rdates(){
return $this->hasMany('AppModelsRDate','reservation_id','id');
}
}
rdate model:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class RDate extends Model
{
protected $table = 'r_dates';
protected $casts = [
'reservation_id' => 'int'
];
protected $dates = [
'date'
];
protected $fillable = [
'reservation_id',
'date',
'created_by',
'updated_by'
];
public function rtypes(){
return $this->hasMany('AppModelsRtype','r_date_id','id');
}
public function reservations(){
return $this->belongsTo('AppModelsReservation','reservation_id','id');
}
}
and finally rtype model:
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Rtype extends Model
{
protected $table = 'r_types';
protected $casts = [
'r_date_id' => 'int',
'num_rooms' => 'int'
];
protected $fillable = [
'r_date_id',
'num_rooms',
'created_by',
'updated_by'
];
public function rdates(){
return $this->belongsTo('AppModelsRDate','r_date_id','id');
}
}