php – I defined many to many relationship between two table and i successfully ran the migration and seeder… but it didn’t work

I want to create many to many relationships between user and schedule

This is my user model

<?php

namespace AppModels;

use AppModelsMajor;
use AppModelsScore;
use AppModelsSchedule;
use LaravelSanctumHasApiTokens;
use IlluminateNotificationsNotifiable;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentCastsAttribute;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    

    protected $guarded=['id'];
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function getRouteKeyName()
    {
        return 'name';
    }

    public function score(){
        return $this->hasMany(Score::class);
    }
    
    public function major(){
        return $this->hasOne(Major::class,'id','major_id');
    }

    public function schedule(){
        return $this->belongsToMany(Schedule::class,'schedule_user','user_id','schedule_id');
        // 'schedule_user','user_id','schedule_id'
    }

    protected function type(): Attribute
    {
        return new Attribute(
            get: fn ($value) =>  ["mahasiswa", "dosen","admin"][$value],
        );
    }
}

this is my schedule model

<?php

namespace AppModels;

use AppModelsUser;
use AppModelsCourse;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentFactoriesHasFactory;

class Schedule extends Model
{
    use HasFactory;
    protected $guarded=['id'];

    public function course(){
        return $this->belongsTo(Course::class);
    }
    public function user(){
        return $this->belongsToMany(User::class,'schedule_user','schedule_id','user_id');
    }
    
}

create_users_table

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            // $table->unsignedBigInteger('major_id');
            $table->foreignId('major_id')->constrained('majors');
            // $table->foreign('major_id')->references('id')->on('majors');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->default('password123');
            $table->bigInteger('nrp');
            $table->string('address');
            $table->integer('generation');
            $table->integer('type')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

create_schedules_table

<!-- create_schedules_table -->
<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateSchedulesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schedules', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->nullable();
            $table->foreignId('course_id')->constrained('courses')->nullable();
            $table->timestamps();
            $table->string('Hari');
            $table->string('Jam');
            

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('schedules');
    }
}

create_schecule_user_table.php

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateScheduleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schedule_user', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->foreignId('user_id')->constrained('users')->nullable();
            $table->foreignId('schedule_id')->constrained('schedules')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('schedule_user');
    }
}

here is my controller.. i try to show the user schedule where user’s id=1

<?php

namespace AppHttpControllers;

use AppModelsSchedule;
use AppModelsUser;
use IlluminateHttpRequest;

class ScheduleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        //
        $user=User::find(1);
        return view('schedule.index',[

            'title'=>'Jadwal Kuliah',
            'schedules'=>$user->schedule
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  AppModelsSchedule  $schedule
     * @return IlluminateHttpResponse
     */
    public function show(Schedule $schedule)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppModelsSchedule  $schedule
     * @return IlluminateHttpResponse
     */
    public function edit(Schedule $schedule)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppModelsSchedule  $schedule
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, Schedule $schedule)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  AppModelsSchedule  $schedule
     * @return IlluminateHttpResponse
     */
    public function destroy(Schedule $schedule)
    {
        //
    }
}

and here’s the schedule.index

@extends('dashboard.layouts.main')

@section('container')
<h3>schedule Kuliah {{auth()->user()->name}}</h3>
<table class="table align-items-center justify-content-center mb-0">
    <thead>
      <tr>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Mata Kuliah</th>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Hari</th>
        <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Jam</th>
        <th></th>
      </tr>
    </thead>
    <tbody>

    @foreach ($schedules as $schedule)
      <tr>
        <td>
          <div class="d-flex px-2">
            <div class="my-auto">
              <h6 class="mb-0 text-sm">{{$schedule->course->nama_mata_kuliah}}</h6>
            </div>
          </div>
        </td>
        <td>
          <p class="text-sm font-weight-bold mb-0">{{ $jadwak->hari }}</p>
        </td>
        <td>
          <span class="text-xs font-weight-bold">{{ $schedule->jam }}</span>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>

@endsection

the view not displaying any user’s schedule. When i check in the terminal using php artisan tinker, the Schedule::first()->user returned: all:[]

Leave a Comment