简体   繁体   中英

How can I let users edit and delete posts and comments in a selfmade blog?

I built a website with an announcement/blog side and don't have any delete/edit functionality yet, I've tried several things, but they either don't work properly or not at all.

I've tried editting posts/comment with a dropdown WYSIWYG editor, if you click the edit button it would expand the comment with Jquery and then the user could edit their comment. The issue is that this only works with the top comment since every editting div/form has the same ID.

Deleting has the issue that the comments are connected to posts with foreign key constraints, so if I try to delete a post it won't let me because of the foreign keys.

//Delete functions

public function deleteannouncement(Announcement $announcement, $id){

        $announcements = Announcement::findOrFail($id);
        $replies = Reply::where('post_id', $announcement->id);
        $announcements->delete($replies, $announcements);

        return redirect('/mededelingen/')->with('success','Bericht succesvol verwijderd!');
    }

    public function deletereply($id){

        $replies = Reply::findOrFail($id);
        $replies->delete($replies);

        return redirect(url()->previous())->with('success','Opmerking succesvol verwijderd!');
    }

//Edit function Comments/Replies

public function postSummernoteeditorReply(Request $request, $id){
        $this->validate($request, [
            'detail' => 'required',
        ]);

        $detail=$request->detail;
        $dom = new \DomDocument();
        $dom->loadHtml( mb_convert_encoding($detail, 'HTML-ENTITIES', "UTF-8"), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
        $images = $dom->getElementsByTagName('img');

        foreach($images as $img){
            $src = $img->getAttribute('src');

            // if the img source is 'data-url'
            if(preg_match('/data:image/', $src)){

                // get the mimetype
                preg_match('/data:image\/(?<mime>.*?)\;/', $src, $groups);
                $mimetype = $groups['mime'];

                // Generating a random filename
                $filename = uniqid();
                $filepath = "/img/blog/$filename.$mimetype";

                // @see http://image.intervention.io/api/
                $image = Image::make($src)
                    // resize if required
                    /* ->resize(300, 200) */
                    ->encode($mimetype, 100)    // encode file to the specified mimetype
                    ->save(public_path($filepath));

                $new_src = asset($filepath);
                $img->removeAttribute('src');
                $img->setAttribute('src', $new_src);

            } // <!--endif
        } // <!--endforeach

        $detail = $dom->saveHTML();
        $summernote = Summernote::find($id);
        $summernote->post_content = $detail;
        //dd($summernote->post_content);
        //dd($summernote->post_id);
        $summernote->update();

        return redirect(url()->previous());
}

//View with the comments & edit form/WYSIWYG

                <div class="card-body">
                    @foreach($replies as $reply)
                        <div class="announcement">
                            @if(Auth::user()->admin == 1 || Auth::user()->id == $reply->user_id)
                                <a href="/reactie/destroy/{{$reply->id}}" class="float-right"><i class="fal fa-dumpster"></i></a>
                            @endif
                            @if(Auth::user()->id == $reply->user_id)
                            <i class="fal fa-pencil float-right" id="yeet" class="float-right" style="color: #007ac3; margin-right: 10px;"></i>
                            @endif
                            <p style="font-size: 0.8rem;">{{date("j F Y", strtotime($reply->created_at))}} | Geplaatst door <span>{{$reply->username}}</span></p>
                            <p style="margin-top: -10px;">{!! $reply->post_content !!}</p>
                            @if(Auth::user()->id == $reply->user_id)
                            <div class="reply-expand" style="display: none;">
                                <form method="POST" action="{{ route('Reply Edit', ['id' => $reply->id]) }}">
                                    @csrf
                                    <div class="col-xs-12 col-sm-12 col-md-12">
                                        <div class="form-group">
                                            <strong>Reactie Aanpassen:</strong>
                                            <textarea class="form-control summernote" name="detail">{!! $reply->post_content !!}</textarea>
                                        </div>
                                    </div>
                                    <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                                        <button type="submit" class="btn btn-primary pull-right" style="border-radius: 0px; box-shadow: 0px 1px 10px -4px #000000;">Aanpassen</button>
                                    </div>
                                </form>
                            </div>
                            @endif
                            <hr>
                        </div>
                    @endforeach
                        {{ $replies->links() }}
                    <form method="POST" action="{{ route('editor.post', ['id' => $announcements->id]) }}">
                        @csrf
                        <div class="col-xs-12 col-sm-12 col-md-12">
                            <div class="form-group">
                                <strong>Reactie:</strong>
                                <textarea class="form-control summernote" name="detail"></textarea>
                            </div>
                        </div>
                        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                            <button type="submit" class="btn btn-primary pull-right" style="border-radius: 0px; box-shadow: 0px 1px 10px -4px #000000;">Reageer</button>
                        </div>
                    </form>
                </div>

//Jquery for both the WYSIWYG and my edit toggle

        $(document).ready(function() {
            $('.summernote').summernote({
                height: 400,
            });
            $('#yeet').click(function() {
                $('.reply-expand').toggle("slide");
            });
        });

What I hope to achieve is having the possibility for admins and the OP to be able to delete their posts without having the Foreign Key Constraint issue. If the posts gets deleted, the comments need to be deleted with it.

The Edit function working in my @foreach so each comment will be editable by users.

Thank you in advance and sorry for the long question :)

This is not a problem related to Laravel or your application design, you need to inform your SGBD ( Mysql ) that when you delete a record on a certain table, all records related to the deleted one need to be deleted as well. this functionality can be achieved by using the method onDelete('cascade') on your migrations.

https://laravel.com/docs/5.8/migrations#foreign-key-constraints

Schema::table('replies', function (Blueprint $table) {
    $table->autoIncrement('id');
    ....
    $table->foreign('announcement_id')->references('id')->on('announcements')->onDelete('cascade');
});

this way, you'll not need to include this part on your code:

$replies = Reply::where('post_id', $announcement->id);
$announcements->delete($replies, $announcements);

i advise you to check the eloquent relationships in laravel too, it makes managing relations between tables much easier.

https://laravel.com/docs/5.8/eloquent-relationships

for example, if you want to select all the replies of a single annoucement, you just need to write

$annoucement->replies();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM