WhereHas Filter with Laravel Polymorphic Relationships or Filter Relationship Existence


Laravel Polymorphic Relationships Filter by Relationship Existence

Laravel framework is the best PHP framework available today, thanks to Taylor Otwell who developed this magical web framework giving life back to PHP arena, without any doubt , with every new release of Laravel, Taylor used to ship something amazing for developer world, Like wise in the latest Laravel 5.8 release, Taylor Has made it possible to apply relationship existence filter (in technical term, whereHas Filter) with Laravel Polymorphic Relationship which was one of the lacking feature in the previous version of Laravel prior to Laravel 5.8.

This will be very useful and time saving for many developers, reducing the complexity by removing repeated tables in db for storing data for common entities like Comments,Tags,Media etc. by making it possible to share same entity among multiple models with full control over querying the underlying data. Applying WhereHas() Filter conditions to Polymorphic Relationships queries gives you the power to retrieve and present filtered data in every imaginable manner with Laravel Polymorphic Relationships.

Please read one of my previous posts which shows a full example on how to create Polymorphic Relationshipswith Database Design, Model design and defining relationship.

Working with Polymorphic Relations in Laravel 5 - Create,Save,Update,Delete, and Filter Actions

in this post I will show your How to apply whereHas Filter with a Laravel Polymorphic Relationship, for example for a commenting system where a Comment Entity has been shared with Multiple other Models such as Blog and News , it means user can comment on Blog or on News.
As in the version prior to Laravel 5.8 and in my example above, you must be aware how to fetch all the comments from a given Blog Model or News Model, but here I will show how to get all comments without touching parent Model such as News or Blog.


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

You may use the $type parameter to add different constraints depending on the related model types such Blog or News:

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

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

You may sometime need to get all comments by skipping certain type of Models comment, for example assume I have another Entity Video in this case which also shares the Comment Model, I want now get all comments except which are made either News or Blog.

$comments = App\Comment::doesntHaveMorph(
    'commentable', 
    ['App\Blog', 'App\News']
)->get();  


Polymorphic relations can no doubt save a great deal of time and effort when you'd like models to share a particular feature such as documents, notes or contacts on an enterprise system.

If you have any other questions, experience or insights on "Creating , Using Laravel polymorphic relations" please feel free to leave your thoughts in the comments bellow which might be helpful to someone some day!

Written by Akram Wahid 5 years ago

are you looking for a chief cook who can well craft laravel and vuejs, to make some awsome butterscotch,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in

Responses

Be the first one to write a response :(

{{ item.member.name }} - {{ item.created_at_human_readable }}

{{ reply.member.name }} - {{ reply.created_at_human_readable }}