Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

henryoladj's avatar

Sluggable posts appears more than once

I am using a package to generate my slug News Model.php

 public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'subject'
            ]
        ];
    }

NewsController.php

<?php

namespace App\Http\Controllers;

use App\News;
use App\Tag;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class NewsController extends Controller
{
    function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
     //  public function index(Request $request, $tag=null)
     // {   
     //     if($request->has('tags')){
     //         $tag=Tag::find($tag);
     //         $news=$tag->news;
     //    }else{
     //        $news= News::paginate(15);
     //     }
     //     return view('categories.news',compact(['news','tag']));
     // }

    public function index(Request $request, $tag=null)
    {   
        if($tag){
            $tag=Tag::where('name',$tag)->first();
            $news=$tag->news()->latest()->paginate(15);
        }else{
            $news= News::latest()->paginate(15);
        }
        return view('categories.news',compact(['news','tag']));
    }

    // public function index(Request $request)
    // {   
    //     if($request->has('tags')){
    //         $tag=Tag::where('name',$request->tags)->first();
    //         $news=$tag->news;
    //     }else{
    //         $news= News::paginate(15);
    //     }
    //     return view('categories.news',compact('news'));
    // }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {   
        
        return view('news.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //validate

        $this->validate($request,[
            'subject'=>'required|min:10',
            'tags' => 'required',
            'body' => 'required|min:20'

        ]);
        
        //store
        $news=auth()->user()->news()->create($request->all());

        $news->tags()->attach($request->tags);
        //redirect
        return redirect()->route('news.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function show(News $news)
    {   
        
        return view('news.single', compact('news', 'tag'));
    }

    

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function edit(News $news)
    {   
        $totalNews = News::count();
        $totalUsers = User::count();
        return view('news.edit', compact('news'))->with(['sum'=>$totalUsers])->with(['total'=>$totalNews]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, News $news)
    {
        if(auth()->user()->id !== $news->user_id){
            abort(401, "Please Login");
        }

        $this->validate($request,[
            'body' => 'required|min:20'
        ]);

        $news->update($request->all());

        $totalNews = News::count();
        $totalUsers = User::count();

        return redirect()->route('news.show', $news->slug)->withMessage('News Updated')->with(['sum'=>$totalUsers])->with(['total'=>$totalNews]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function destroy(News $news)
    {   
        if(auth()->user()->id !== $news->user_id){
            abort(401, "Please Login");
        }

      
        $news->delete();
        return redirect()->route('news.index');
    }

}

Can anyone tell me and help me with why the posts are appearing more than once?

0 likes
40 replies
Snapey's avatar

What causes a duplicate? They don't appear on their own?

When you EDIT a post, are you sure you are calling the update method and not the store method in your form?

henryoladj's avatar

I call the store when creating the post <form action="{{route('news.store')}}" id="postform" method="post">

and the duplicate happens after i create the posts not during edit

Snapey's avatar

How can it be a duplicate? Surely its whatever you entered when you created it.

henryoladj's avatar

@snapey Let me explain well to you, I have a topic which is "How to make a website" on the news tag. So to make the post on that topic i go to create the post and after i click on Publish, the post appears on the homepage as a single post but on the news tag it appears more than once sometimes it appears like 5 times on that category page but not homepage.

Here is the link to what i am talking about http://7e4010a7.ngrok.io/category/news the post "Sluggable posts appears more than once" appears 4 times with same slug

but on the homepage http://7e4010a7.ngrok.io/ it appears once. How can i solve this 4 times appearance problem?

henryoladj's avatar

@snapey the posts i made on Entertainment category appears on the news Category which is wrong

jlrdw's avatar

Are you sure the extra posts wasn't accidentally inserted while programming all of this.

henryoladj's avatar

It was not because it is not appearing more than once in the database

Snapey's avatar

What controller method extracts the data from the database?

How do you present it in the view?

henryoladj's avatar

@snapey i loop to get it.

<div class="main-body">
            <div class="clearfix">   
                <div class="main-body-post">
                    <div class="home-main"><h3>Latest {{$category}} Updates</h3></div>
                       @foreach($news as $new)
                        <div class="post-real">
                             <a href="{{route('news.show',$new->slug)}}">{{$new->subject}}</a> 
                            <br>
                            <br>
                        </div>  
                        @endforeach               
                </div> 
            </div>             
        </div>

Like that and the controller method is Index

Snapey's avatar

so as you just load all posts, I guess they must be duplicated in the database.

henryoladj's avatar

@snapey yes in the news_tag table which contains news_id and tag_id in my database, it duplicates it. I really do not know why it duplicates.

news_id is the news id tag_id is that tag id

if a news have ID of 1 and tag has ID of 1 it duplicates inside the database

mware's avatar

Instead of creating the news will the all the request data, try creating it with just the data you need and see if thats where the duplication is happening.

$news=auth()->user()->news()->create($request->except(['tags']));
Snapey's avatar

I show it on the view without Tag i guess

If that the case, then the tag pivot is not relevant. Are you sure you do not pass tag to index?

henryoladj's avatar

@snapey I did not, so how do you suggest i store it so that it will not get duplicated?

mware's avatar

Is there a model observer on News that fires when news is created? It's sounds like the attach method is being called twice? Just throwing out thoughts as to why this is happening.

henryoladj's avatar

I think the problem is with the Store method, There is a table that joins the Tag and News Together. On the table the news Id is different from the actual news ID made.

henryoladj's avatar

If the News ID is 20 Tag ID is 1

on the news_tag the News ID is 2 and Tag ID is 1.

henryoladj's avatar

If i should change the ID of the news tag to 0 instead of 1 and make a post under it, then it appears once and not duplicated.

mware's avatar

Did you define the pivot table name on the News and Tag models? It may be looking for a new_tag table. The documentation refers to a role_user table for a many-to-many relationship for roles and users.

henryoladj's avatar

@mware

News.php

public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

Tags.php

public function news()
    {
        return $this->belongsToMany(News::class);
    }
mware's avatar

Theres a few things going on here. Maybe its a typo, but hopefully Tags.php is actually Tag.php. And then you can try this for your relationships:

News.php


public function tags(){
    return $this->belongsToMany(Tag::class, 'news_tag');

}

Tags.php

public function news(){
    return $this->belongsToMany(News::class, 'news_tag');

}
henryoladj's avatar

@mware Using this, the post appears once, let me try to post few things to be sure.

henryoladj's avatar

It was supposed to take the ID of the current news which it is not doing instead it is creating another ID for news in the news_tag table.

Next

Please or to participate in this conversation.