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

devionti's avatar

Trying to get name of a BelongsTo that exists inside a parent - Nova

I have a hotel management module. So basically has location has many rooms, room has many occupants. Inside the occupants resource I want to show the room location.

Inside occupants table I have roomId, while inside rooms table I have locationId, name. I basically want to show the location name.

Occupants Model

    public function room()
    {
        return $this->belongsTo('App\Models\Accommodations\Rooms', 'roomId', 'id');
    }

Rooms Model

  public function location()
    {
        return $this->belongsTo('App\Models\Structures\Locations', 'locationId', 'id');
    }

    public function occupants()
    {
        return $this->hasMany("App\Models\Accommodations\Occupants", 'roomId', 'id');
    }

Location Table Schema

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

Occupants Resource

            BelongsTo::make('Location', 'room', \App\Nova\Accommodations\Room::class)->sortable()->display(function ($room) {
                return $room->location->name;
            })->hideWhenCreating()->hideWhenUpdating(),

Error: Trying to get property 'name' of non-object

Occupants does not have locationId, so I'm getting the location name from the room based on location method in rooms model.

0 likes
0 replies

Please or to participate in this conversation.