risav55
risav55

Reputation: 35

Laravel get data from pivot table many to many relationship

Tables with relationship

I want to get the classes for specific notes. Here note id and class id are in a pivot table.

Note.php

    public function classes()
        {
            return $this->belongsToMany(MyClass::class);
        }

MyClass.php

public function notes()
    {
        return $this->belongsToMany(Note::class);
    }

I am saving the data successfully by

$note->classes()->attach($request->class);

MyClass Migration

Schema::create('my_classes', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();

            $table->boolean('isDeleted')->default(false);
            $table->dateTime('deletedAt')->nullable();
        });

Notes Migration

Schema::create('notes', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description')->nullable();
            $table->string('image')->nullable();

            $table->timestamps();

            $table->boolean('isDeleted')->default(false);
            $table->dateTime('deletedAt')->nullable();
        });

my_class_note migration

Schema::create('my_class_note', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->foreignId('my_class_id')->constrained();
            $table->foreignId('note_id')->constrained();

            $table->timestamps();
        });

Needed help on getting classes for a specific note. One note can have many classes.

Upvotes: 1

Views: 863

Answers (1)

mrhn
mrhn

Reputation: 18916

You can simply access it by using the relationship property, there always will be if you have defined a relationship.

// returns a collection of classes
$classes = Note::find(1)->classes;

In your controller.

return view('yourview', ['classes' => $classes]);

In your view.

@foreach($classes as $class)
    <p>{{$class->name}}</p>
@endforeach

Upvotes: 3

Related Questions