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();

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts

Search

Page Facebook