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');
}
VaccineController
public function schedule()
{
$pets = Pet::get();
return view('Vaccines.schedule', compact('pets'));
}
Migration Pet
Schema::create('pets', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->date('birthdate');
$table->string('color');
$table->date('castration_date');
$table->string('weight');
$table->string('picture')->nullable();
//Foreign Keys
$table->unsignedInteger('breed_id');
$table->foreign('breed_id')->references('id')->on('breeds');
$table->unsignedInteger('gender_id');
$table->foreign('gender_id')->references('id')->on('genders');
$table->unsignedInteger('type_id');
$table->foreign('type_id')->references('id')->on('types');
$table->unsignedInteger('food_id');
$table->foreign('food_id')->references('id')->on('foods');
$table->unsignedInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients');
$table->softDeletes();
$table->timestamps();
});
Migration Vaccine
Schema::create('vaccines', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Migration pets_vaccine
Schema::create('pets_vaccines', function (Blueprint $table) {
$table->increments('id');
$table->date('scheduled_date')->nullable();
$table->date('application_date')->nullable();
//Foreign Keys
$table->unsignedInteger('vaccine_id');
$table->foreign('vaccine_id')->references('id')->on('vaccines');
$table->unsignedInteger('pet_id');
$table->foreign('pet_id')->references('id')->on('pets');
$table->timestamps();
});
And in the view I have this:
@foreach ($pets as $pet)
Mascota: {{$pet->name}} Vacuna: {{$pet->pivot->scheduled_date}} <br>
@endforeach
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.