jeudi 7 octobre 2021

Trying to Save Comments but the application redirects me to an empty page

I've made a blog and now I'm trying to implement a comment section. I want it so that when the user tries to post, it's saves the comment and redirects the user to the same page. But when I write a comment and try to post it, the application redirects me to a different page. I'm learning how to make a blog with laravel, so I don't know when to use url and when to use routes. Here's the code that I've written.

@auth
        <div class="card ml-5 col-lg-8">
            <ul class="list-group list-group-horizontal">
                <h5 class="list-group-item active">
                    Comments
                <h5>
                <div class="card-body">
                <form method="post" action="">
                @csrf
                    <textarea name="comment" class="form-control py-5"></textarea>
                    <input type="submit" class="btn btn-primary mt-3">
                </div>
                    
            </ul>
        </div>
        @endauth
        <div class="card ml-5 col-lg-8">
            <h5 class="card-header mb-4">Comments<span class="badge badge-info ml-2"> </span></h5>
            <div class="card-body mt-3">
                @if($blog->comments)
                    @foreach($blog->comments as $comment)
                    <blockquote class="blockquote">
                        <p class="mb-0"></p>
                        <footer class="blockquote-footer">Username</footer>
                    </blockquote>
                    <hr>
                    @endforeach
                @endif
            </div>
        </div>

**BlogController**
function save_comment(Request $request,$slug,$id)
{
    $request->validate([
        'comment'=>'required',
    ]);
    $data = new Comment;
    $data->user_id=$request->user()->id;
    $data->post_id=$id;
    $data->comment=$request->comment;
    $data->save();
    return back();
}

**Routes**
Route::get('/blog/', [App\Http\Controllers\BlogController::class, 'index'])->name('blog');
Route::get('blogs/{slug}','App\Http\Controllers\BlogController@getArticles')->name('article.show');
Route::get('blog.update/{id}','App\Http\Controllers\BlogController@edit');
Route::put('blog.update/{id}','App\Http\Controllers\BlogController@update');
Route::post('save_comment/{slug}/{id}','App\Http\Controllers\BlogController@save_comment')->name('save_comment');
Route::get('/admin/blog', 'App\Http\Controllers\BlogController@getBlog')->name('admin.blog');

If there's someone willing to assist come up with a solution to this problem, please assist me. I think the problem lies where I've written the url lies. When I change the url to route, it gives me an error of route not defined. Route::resource('/blog','App\Http\Controllers\BlogController');



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire