Dave Wize's avatar

Count() a has many table without loading the data.

I want to do an @if that would check if a thread has more then 10 messages. however I don't want to load all messages (it might be a ton), I'm using my own pagination as I want to get infinate pagination (through livewire). Is there a way to accomplish this simple if check without loading all messages?

                @if (count($channel->message) >= 10)
                <button class="bg-[#2780A8] group items-center justify-center text-sm py-2 flex mx-auto gap-2 rounded-lg font-poppins font-medium text-white px-5" wire:click="showMore">
                    <span>Show previous</span>
                    <span class="transition-all group-hover:translate-x-1"><img src="/img/setting/right-arrow.svg" alt="right-arrow" /></span>
                </button>
                @endif
0 likes
2 replies
yeasirarafat-dev's avatar

Laravel's eloquent relationship has a method called withCount with that you can count.

$channel = Channel::withCount('message')->first();
$channel->message_count;
Dave Wize's avatar
Dave Wize
OP
Best Answer
Level 18

@yeasirarafat-dev Thanks for your help. I have actually done something slightly different because your approach wouldn't work in my scenario. as I was in a livewire component, and I needed to save the state. Here is how I did it in the livewire class.

    public function mount(Channel $channel)
    {
        $this->channel = $channel;
        $this->channel->loadCount('message');
        $this->totalMessages = $this->channel->message_count;
    }

And this is the view

                @if ($totalMessages >= 10)
                   <button>....</button>
                @endif

Please or to participate in this conversation.