New

Just launched: Vueblocks, a brand-new search engine for Vue packages! Explore Vueblocks →

rackbeat/laravel-morph-where-has

Fix whereHas for morphTo relations.
61,607 7
Install
composer require rackbeat/laravel-morph-where-has
Latest Version:2.0
PHP:>=7.1
Laravel:6 – 9
Older releases:5
License:MIT
Last Updated:Nov 26, 2022
Links: GitHub  ·  Packagist
Maintainer: lasserafn

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.

Total Downloads Latest Stable Version License

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.

Related Packages

yadakhov/insert-on-duplicate-key

A trait for MySQL INSERT ON DUPLICATE KEY UPDATE.

3,123,272 275
terranc/eloquent-insert-on-duplicate-key

Macros for INSERT ON DUPLICATE KEY UPDATE and INSERT IGNORE with Eloquent

2,001 0
pindab0ter/constrained-morph-to-for-laravel

Constrained polymorphic relationships for Laravel Eloquent - limit morphTo relat...

13,109 3
zara-4/laravel-lazy-mysql

A lazy mysql based Eloquent model and Query builder for Laravel

7,997 10
caloskao/migrate-specific

Easily perform database migrations of specific migration files in the Laravel fr...

16,240 7

Version History

Version Released PHP Laravel License
2.0 >=7.1 ^6.0|^7.0|^8.0|^9.0 MIT
1.6 >=7.1 ^5.6|^5.7|^5.8|^6.0|^7.0|^8.0 MIT
1.5 >=7.1 ^5.6|^5.7|^5.8|^6.0|^7.0|^8.0 MIT
1.4 >=7.1 ^5.6|^5.7|^5.8|^6.0|^7.0|^8.0 MIT
1.3 >=7.1 ^5.6|^5.7|^5.8|^6.0|^7.0 MIT