Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Morph Where Has Laravel Package

rackbeat/laravel-morph-where-has

View on GitHub
Deep Wiki
Context7

Use whereHas for morphed relationships in Laravel

Usually, you cant say whereHas('contact') if contact is a morphTo relationship. This package aims to fix that.

Installation

You just require using composer and you're good to go!

composer require rackbeat/laravel-morph-where-has

The Service Provider is automatically registered.

Usage

1. Add possible variations in your model

The problem, is that the morph relationship can have a hard time determining how to handle the whereHas call.

Our solution, is that you define every possible morphed class. Like so:

<?php

class Invoice extends Model {
    // Old morph relation
    public function owner() {
        return $this->morphTo('owner'); 
    }
    
    // New solution
    public function customer() {
        return $this->morphTo('owner')->forClass(App\Customer::class);
    }
    
    public function supplier() {
        return $this->morphTo('owner')->forClass(App\Supplier::class);
    }
}

2. Use whereHas

Invoice::whereHas('supplier', function($query) {
    $query->whereName('John Doe');
})->get();

This will correctly query a relation with the type and any queries you've added.

Requirements

  • PHP >= 7.1

Inspiration

Solution based upon work by github@thisdotvoid - modified to fix some common issues.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle