Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Fetch results based on the existence/absence of the MorphTo relationships in Laravel

 

To query the existence of MorphTo relationships, you may use the whereHasMorph, whereDoesntHaveMorph methods and its corresponding methods:

Retrieve comments associated to posts or videos with a title like foo%...


$comments = App\Models\Comment::whereHasMorph(
    'commentable',
    ['App\Models\Post', 'App\Models\Video'],
    function (Builder $query) {
        $query->where('title', 'like', 'foo%');
    }
)->get();

 

Retrieve comments associated to posts with a title not like foo%...


$comments = App\Models\Comment::whereDoesntHaveMorph(
    'commentable',
    'App\Models\Post',
    function (Builder $query) {
        $query->where('title', 'like', 'foo%');
    }
)->get();

 

You may use the $type parameter to add different constraints depending on the related model:

 

use Illuminate\Database\Eloquent\Builder;

$comments = App\Models\Comment::whereHasMorph(
    'commentable',
    ['App\Models\Post', 'App\Models\Video'],
    function (Builder $query, $type) {
        $query->where('title', 'like', 'foo%');

        if ($type === 'App\Models\Post') {
            $query->orWhere('content', 'like', 'foo%');
        }
    }
)->get();

 

Instead of passing an array of possible polymorphic models, you may provide * as a wildcard and let Laravel retrieve all the possible polymorphic types from the database.

Laravel will execute an additional query in order to perform this operation:

 

use Illuminate\Database\Eloquent\Builder;

$comments = App\Models\Comment::whereHasMorph('commentable', '*', function (Builder $query) {
    $query->where('title', 'like', 'foo%');
})->get();

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon