How to get nested relation record for ajax request in laravel?

web pakistan

I have Model Ticket in which user explain issue.

Ticket.php

class Ticket extends Model
{
    protected $table = 'tickets';
    /**
     * @var array
     */
    protected $guarded = [];

    /**
     * @var array
     */
    protected $hidden = [
        'created_at', 'updated_at'
    ];


    public function ticket_replies()
    {
        return $this->hasMany(TicketReply::class, 'ticket_id');
    }

    public function ticket_assigned_agents()
    {
        return $this->hasMany(TicketAssignedAgent::class, 'ticket_id');
    }
}

There is another model TicketReply.php

class TicketReply extends Model
{
    protected $table = 'ticket_replies';
    /**
     * @var array
     */
    protected $guarded = [];

    /**
     * @var array
     */
    protected $hidden = [
        'created_at', 'updated_at'
    ];

    public function staffs(){
        return $this->belongsTo(Staff::class,'user_id');
    }
    public function ticket()
    {
        return $this->belongsTo(Ticket::class, 'ticket_id');
    }
}

Now I want to get staff name from ticket reply

Query

public function getReplies($ticket_id)
    {
        $ticket =  Ticket::where('id',$ticket_id)->with('ticket_replies')->first();
        return response()->json($ticket);
    }

I want to get staff name from TicketReply model in ajax success.

$.each(ticket.ticket_replies, function(index, reply) {
    console.log(reply.staffs.name);
}

But it is not working. What can I do about it?

zahid hasan emon

eager load the nested relationship

public function getReplies($ticket_id)
{
    $ticket =  Ticket::where('id',$ticket_id)->with(['ticket_replies','ticket_replies.staffs'])->first();
    return response()->json($ticket);
}

and then do the same you are doing

$.each(ticket.ticket_replies, function(index, reply) {
    console.log(reply.staffs.name);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related