In laravel to check query the existence of "morph to" relationships, we can use whereHasMorph and whereDoesntHaveMorph method. In this tutorial, I will show you how we can use whereDoesntHaveMorph and whereHasMorph to check polymorphic relationship existence. Laravel provides a very convenient way of checking polymorphic relationship existence using whereHasMorph.

Lets see the example code of laravel wherehasmorph example:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Comment;
use App\Models\Post;
use App\Models\Video;
use Illuminate\Database\Eloquent\Builder;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Comment::whereHasMorph(
                    'commentable',
                    [Post::class, Video::class],
                    function (Builder $query) {
                        $query->where('title', 'like', 'code%');
                    }
                )->get();
    }
}

 

Or we can use whereDoesntHaveMorph like this:

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

 

Instead of the passing of a collection of models array, we can provide * as a wildcard value like that:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Comment;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Comment::whereHasMorph('commentable', '*', function ($query) {
            $query->where('title', 'like', 'foo%');
        })->get();
    }
}

 

Read also: Laravel DoesntHave And WhereDoesntHave Example

 

Conclusion

Now we know laravel wherehasmorph example. Hope this laravel eloquent wherehasmorph example tutorial will help you to create how to use wherehasmorph in laravel.