Two component with same eloquent

I have two different components named address and tel on same page and route with same eloquent.

<livewire:address-comp />
<livewire:tel-comp />
the address component show

public $general;
  in mount funtion : $general= General::first();
$general->name;

the tel component show

public $general;
 in mount funtion : $general= General::first();
$general->tel;

app load each eloquent in mount function, my question goes that is this style inappropriate and makes app slow? repeating reading from the database is a bad solution? @if then what is the best?

thank you.

Generally, yeah it’s bad practice to have duplicated queries. From a performance standpoint, I don’t think it’s the end of the world to duplicate pulling a single record, as the performance difference is almost non existent unless you’re working with huge models and relationships/joins

The easy fix is to call General::first() in your controller and pass it to your view, then pass it into your component in the mount.

A more involved semi fix is to start leveraging caching, whether on your own or using a package to make it easier, which will help negate the performance hit even more.

Personally, I’d recommend doing both at some point.

thank you. for me, performance is a must. I try to find the best solutions for every situation to leverage performance obstacles.

Here’s a shortcut helper function I add to all of my models that you could use to pull single values:

    /**
     * Returns a single value from a model found by id so you
     * don't have to load a whole model instance.
     *
     * @param string $property
     * @param integer $id
     * @return mixed
     */
    public static function single(string $property, int $id)
    {
        return self::whereId($id)->value($property);
    }

Example $this->name = General::single('name', 1);

thank you. is there anyway to see data in console as console.log(‘blabla’) of livewire functions or just dd(‘blabla’) ?

Kind of, you can see the values of public properties livewire.components.componentsById.{componentId}.data. You can just do livewire.components.componentsById to see the ids or just tree view though each component and the data.

Other than that though, everything else is on the back end will be dd().

1 Like