Search code examples
laraveleloquent

How to check if no tags eager parameter were passed in request?


On Laravel/Livewire site I read data with possible eager loading of tags :

    $this->postList = Post
        ::orderBy('title')
        ->with('tags')
        ->getByTitle('%search%')
        ->select('id', 'post_category_id', 'title', 'slug', 'image', 'published', 'created_at', 'creator_id')
        ->paginate(10)
        ->through(function ($postItem) {
            $postItem->image = (new CheckModelImage())->get($postItem->image, get_class($postItem));
            return $postItem;
        });

and in template file I call other component with tags parameter passed:

    @livewire('model-tag', ['id'=>$post->id, 'tags' => $post->tags], key($post->id))

If in top request there are no tags eager parameter used in which way can I to check it ?

I tried to check inside of model-ag component using isset method:

class ModelTag extends Component
{
    use AppCommonTrait;

    public int $id;
    public $tags;

    public $modelTaggables = [];

    public function render(): View
    {
        return view('livewire.model-tag');
    }

    public function mount(int $id, ?\Illuminate\Database\Eloquent\Collection  $tags = null)
    {
        $this->id = $id;
        $this->tags = $tags;
        $this->getData();
    }

    protected function getData(): void
    {
        if(isset($this->tags)) { // I CHECK HERE _ BUT IT ALWAYS VALID
            $this->modelTaggables = $this->tags;
        }   else {
            $this->modelTaggables = Taggable
                ->getByTaggableId($this->id)
                ->with('tag')
                ->get()
                ->map(function ($TaggableItem) {
                    return ['id' => $TaggableItem->tag_id, 'name' => $TaggableItem->tag->name];
                });
        }
    }
}

I search method like whenLoaded in resources...

Are there ?

"laravel/framework": "^10.48.7",
"livewire/livewire": "^3.4.10",

Solution

  • In all your requests that call your model tag, you pass the parameter tag. If your Post object has no tag, it will return an empty array instead of null.

    So, isset([]) always return true;

    You can use the blank method, if(! blank($this->tags)) {

    And you can use Laravel method exists() to check if a post with tags exist.

    Example:

    $post->tags()->exists()

    EDITED:

    To use the $post->tags() you need the relation defined in your model.

    https://laravel.com/docs/11.x/eloquent-relationships#defining-relationships https://laravel.com/docs/11.x/queries#determining-if-records-exist