user8310317
user8310317

Reputation:

Property [owner] does not exist on this collection instance

I'm having a bit of difficulty grasping exactly what Laravel is trying to communicate here and how Eloquent is building/attaching these relationships.

Property [owner] does not exist on this collection instance.

I'm creating a customer support inbox where customers can send tickets in and administrators can respond back.

I'd like to be able to pull the name & some details of the user in the message so, well, the rep knows who they are talking to. Currently there are three tables in play: tickets, users, & replies. I'll break down the structure here as well:

Tickets: id, user_id, body, active (boolean), datestuff... | relates to the Ticket model
replies: id, user_id, ticket_id, body, datestuff | relates to the Reply model.

I've defined the relationship in the Ticket model of $this->belongsTo(User::class,'user_id'); via a public method of owner

public function owner()
    {
        // ESTABLISH RELATIONSHIP

        $this->belongsTo(User::class, 'user_id');

    }

But when I attempt to retrieve the below I retrieve the error in the title. From the TicketsController

$tickets = Ticket::latest()->get();
return $tickets->owner;

And am unable to {{ $ticket->owner->first_name }} or any details on the user that I'd like to pull.

Either my fundamental understanding of Eloquent is incorrect or there are other things that need to be assigned in order to enable this functionality?

I was following along with this episode from Laracast here substituting the Thread for Ticket but Reply namespace stayed. Though Instead of retrieving the user data associated with the reply I'm retrieving the user data of the initial ticket.

https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/3

Upvotes: 1

Views: 3746

Answers (1)

ceejayoz
ceejayoz

Reputation: 180004

$tickets = Ticket::latest()->get();
return $tickets->owner;

This code grabs a collection of tickets. Each ticket in that collection has its own owner.

foreach($tickets as $ticket) {
    // this is where you have $ticket->owner;
}

Your owner() function is also not returning the relationship - it creates one, but does nothing with it. This'll work:

public function owner() {
    return $this->belongsTo(User::class, 'user_id');
}

Upvotes: 1

Related Questions