rackbeat / laravel-morph-where-has
Fix whereHas for morphTo relations.
Installs: 47 430
Dependents: 0
Suggesters: 0
Security: 0
Stars: 7
Watchers: 2
Forks: 1
Open Issues: 2
Requires
- php: >=7.1
- illuminate/contracts: ^6.0|^7.0|^8.0|^9.0
- illuminate/database: ^6.0|^7.0|^8.0|^9.0
- illuminate/support: ^6.0|^7.0|^8.0|^9.0
Requires (Dev)
- phpunit/phpunit: ^7.0
- satooshi/php-coveralls: ^1.0
README
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.