Working with form in laravel

Hello World, Welcome to this website. Today i am going to create a tutorial in which we will create form and submit form data in database with validation in laravel. In my recent tutorials, I am creating a blog application.In this tutorial, i will implement the add comment section in this blog application. so lets start to working with form in laravel.

I have divided this tutorial in following steps,

  • Create Add Comment form in post detail page
  • Setup Route to submit the comment form
  • Setup Post Controller to submit form and save data in database
  • Run the project

Create Add Comment form in post detail page

In this section, we will create a comment form in post detail template.

  • Open /resources/post-detail.blade.php file and add add the following code just below the comments list.
<hr />
        <h3 class="mt-4 pb-2" id="commentSection">Add Comment</h3>
        <form method="post" action="{{ url('submit-comment/'.$postDetail->id) }}" class="mb-4">
            {{ csrf_field() }}
                <p class="alert alert-success">{{ session('success') }}</p>
                <div class="alert alert-danger">
                    @foreach($errors->all() as $error)
                        <p>{{ $error }}</p>
            <table class="table table-bordered">
                    <th>Email <span class="text-danger">*</span></th>
                    <td><input type="text" name="email" class="form-control" /></td>
                    <th>Comment <span class="text-danger">*</span></th>
                    <td><textarea class="form-control" name="comment"></textarea></td>
                    <td colspan="2">
                        <input type="submit" class="btn btn-primary" />
        {{-- Comment Form End --}}

Setup Route to submit the comment form

In this step, we will setup route for submitting form. Here we are submitting comment form with post method so following will be our code for routes/web.php.

// Submit Comment

Setup Post Controller to submit form and save data in database

In this step, we will receive the submitted data in post controller and save in the database with Eloquent.

  • Open PostController.php file and add the following submit_comment method code in it.
// Submit Comment
    function submit_comment(Request $request,$post_id){
        $post=new Comment;
        return redirect('post-detail/'.$post_id.'#commentSection')->with('success','Comment has been saved.');

Run the project

  • Open your project in the browser.
  • Try to add comment data in form.
  • If you leave the form empty then it will throw errors and if you submit the form then you will see the success.

I hope you are enjoying my tutorials. Please add your feedback in the comment section. Thank you 🙂 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *