Problem with pivot table in laravel 5.7


I am doing a project for the university and I have a problem working with a pivot table, it is the relationship between Vaccines (Vaccine) and Pets (Pet), it is a relationship of many to much, believe the migrations of both Vaccine and of Pet, and the pivot table pets_vaccines. Create the models and their relationships but when I try to occupy the relationship it does not work. Also in the table pets_vaccines I have 2 data (scheduled_date and application_date) that I need to occupy.

My idea is to have a view where it shows all the data of that pivot table using Eloquent, but I can not enter the data of the pivot table or the data of another table of the relationship (that is, if I occupy pets) I can not access the vaccine data and vice versa).

I will leave the codes of everything I occupy for this:

Vaccine Model

public function pets(){
        return $this->belongsToMany('App\Pets');

Pet Model

public function vaccines(){
        return $this->belongsToMany('App\Vaccine')->withPivot('scheduled_date');


public function schedule()
        $pets = Pet::get();

        return view('Vaccines.schedule', compact('pets'));

Migration Pet

Schema::create('pets', function (Blueprint $table) {

        //Foreign Keys








Migration Vaccine

Schema::create('vaccines', function (Blueprint $table) {


Migration pets_vaccine

Schema::create('pets_vaccines', function (Blueprint $table) {

        //Foreign Keys




And in the view I have this:

 @foreach ($pets as $pet)
    Mascota: {{$pet->name}}  Vacuna: {{$pet->pivot->scheduled_date}} <br>

Here, the "scheduled_date" gives me an error, but if I remove it, it stops giving me the error but it does not show what I want.

asked by Fabian Alvarado Donoso 31.12.2018 в 20:43

1 answer


According to what I see in the code, you are only calling the pet model only, you must call the relationship and probably iterate over it to see its data:

(Considering that it is many to many, in theory there could be more than one record).

@foreach ($pets as $pet)
  Mascota: {{$pet->name}}

  @foreach ($pets->vaccines as $vaccine)
    {{ $vaccines->pivot->scheduled_at }}


Most likely you need to do Eager Loading, although it depends on how it is designed or the amount of information:

answered by 31.12.2018 / 22:05