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

Moenchfracht's avatar

Relationships not working (LogicException?)

Hello. I try to build a relationship between my tables users (original from laravel) and collectionson Laravel 5.6.

Schema collections:

        Schema::create('collections', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('location');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
            $table->timestamps();
        });

The Collection model:

    public function user() {
        $this->belongsTo('\App\User');
    }

The User model:

    public function collection() {
        $this->hasMany('\App\Collection');
    }

I try to get the user->name using artisan tinker:

>>>  $collection->user()->get();
PHP Error:  Call to a member function get() on null on line 1
>>>  $collection->user()->name;
PHP Notice:  Trying to get property of non-object on line 1
>>> $collection->user->name;
LogicException with message 'App\Collection::user must return a relationship instance.'

Where is my mistake? Thanks!

0 likes
3 replies
rumm.an's avatar
rumm.an
Best Answer
Level 17

You are not returning anything from user() function in your Collection. Seems like you forgot to place return that I often do. :D

Moenchfracht's avatar

It's from here: $collection = App\Collection::find(1);

And it returns:

=> App\Collection {#769
     id: 1,
     name: "TestCollection",
     location: "Herg",
     user_id: 1,
     created_at: "2018-02-24 20:01:36",
     updated_at: "2018-02-24 20:01:36",
   }

Please or to participate in this conversation.