Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

Why my relation in laravel 5.8 not working?

Look at my codes and demo.

I have three tables categories and knowledge_rooms and category_knowledge_room. And all their data is stored.

category

categories table

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name_fa');
        $table->string('name_en');
        $table->integer('parent_id');
        $table->string('icon')->nullable();
        $table->timestamps();
    });
}

knowledge_rooms table

public function up()
{
    Schema::create('knowledge_rooms', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->string('lang');
        $table->text('body');
        $table->string('image');
        $table->string('slug');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });

    Schema::create('category_knowledge_room', function (Blueprint $table) {
        $table->bigInteger('category_id')->unsigned();
        $table->bigInteger('knowledge_room_id')->unsigned();
        $table->primary(['category_id', 'knowledge_room_id']);
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->foreign('knowledge_room_id')->references('id')->on('knowledge_rooms')->onDelete('cascade');
    });
}

AppServiceProvider.php

public function register()
{
    Schema::defaultStringLength(191);
    view()->composer('*', function($view) {
        $view->with('menus', Category::with('knowledgeRooms')->whereParent_id(0)->get());
    });
}

Category.php

public function knowledgeRooms()
{
    return $this->belongsToMany(KnowledgeRoom::class);
}

master.blade.php

@foreach($menus as $menu)
    @foreach($menu->getChild as $submenu)
        @foreach($submenu->knowledgeRooms as $knowledgeRoom)
            {{ dd($knowledgeRoom) }}
        @endforeach
    @endforeach
@endforeach

web.php

Route::view('/', 'Home.master')->name('index');

But I see this demo, it is white page.

blank page

0 likes
0 replies

Please or to participate in this conversation.