Table of contents

laravel wherehas

In this post, you will learn how to implement Laravel Eloquent whereHas() condition in this method you can able to display the existing relations of a specific record. For example, if you have a ticket and that ticket has a conversation and you want to update a specific conversation. But before doing it you need to ensure that the conversation you want to update belongs to a ticket.

 

So in my below example, you will see how we use the Laravel whereHas() condition.

 

$ticketId = 1;
$convoId = 1;


$ticket = Ticket::where('id', $ticketId)->with('conversations', function($query) use($convoId) {
    $query->where('id', $convoId);
})->whereHas('conversations', function (Builder $query) use($convoId){
    $query->where('id', $convoId);
})->firstOrFail();

$convo = $ticket->conversations->first();

$convo->message = 'updated convo';
$convo->save();

 

As you can see I have condition first with $ticketId and using the with() method of eloquent then apply the whereHas() method so that I only display a specific conversation with $convoId.

 

That's pretty much it. I hope it helps. Thank you for reading :)