Search code examples
laravellaravel-8laravel-livewire

hide clone post in index view blade


I have a clone function in my livewire show blade , so when a user clone the post , I don't want the clone post to show in the general post view blade

Post::get();

view blade

@foreach($posts as $post)
    {{ $post->title }}
@endforeach
``
 (

I won't like to have same post in the index

I only want to display the user clone post in there profile

how can I do this livewire components

public function clone($id)
{
    $post = Post::find($id);
    $newPost = $post->replicate();
    $newPost->created_at = Carbon::now();
    $newPost->save();
}

Solution

  • You need a way to identify if a post was cloned or not. To achieve this, you can add a field cloned_post_id to your posts table, then when you clone it, set the ID from the originating post.

    Once you have this data, you can filter out the cloned posts in your register - the best way to achieve this is by adding a relation on the Post model, and check that it does not exist - but you can also check whereNull('cloned_post_id').

    Clone the post,

    public function clone($id)
    {
        $post = Post::find($id);
        $newPost = $post->replicate();
        $newPost->cloned_post_id = $post->id;
        $newPost->updated_at = Carbon::now();
        $newPost->created_at = Carbon::now();
        $newPost->save();
    }
    

    Then in your Post model, add that relation,

    public function clonedPost() 
    {
        $this->belongsTo(Post::class, 'cloned_post_id');
    }
    

    Then in your register, check whereDoesntHave(), to exclude the posts that was cloned,

    $posts = Post::whereDoesntHave('clonedPost')->get();