Home > front end >  Filter the relation in the RouteModelBinding context in the controller method show()
Filter the relation in the RouteModelBinding context in the controller method show()

Time:11-24

I am working on a Laravel8 project with Route Model Binding. It is about Posts. Post has a One To Many (Polymorphic) Relation to the model Comment. Comments have a field approved. This is a Boolean.

How can I display the Post with its Comments that are approved === true. I know I could catch it in the blade with an if condition. But my goal is to filter the comments already in the controller.

    public function show(Post $post)
    {  
        dd( $post->comments );        
        return view('post', ['post' => $post]);
    }

Comment migration, - Model:

    Schema::create('comments', function (Blueprint $table) {
        $table->id();            
        $table->text('comment_content');
        ...
        $table->boolean('approved')->default(false);
        $table->integer('commentable_id');
        $table->string('commentable_type');            
        $table->timestamps();
    });

    // Comment Model
    public function commentable()
    {
        return $this->morphTo();
    }

Post Model

    public function comments()
    {
        return $this->morphMany(PostComment::class, 'commentable');
    }

Expected only the Comments which approved.

CodePudding user response:

even if it is morph relation, you can load it using load method:

$post->load(['comments' => function ($query) {
    $query->where('approved', true);
}]);

CodePudding user response:

I believe you can load in only approved comments on the relationship like so:

public function comments()
{
    return $this->morphMany(PostComment::class, 'commentable')
        ->where('approved', 1);
}

MorphMany is from Laravel's HasRelationships class, and you should be able to tag on a where condition to filter it as you need.

  • Related