Laravel Multiple Data Edit Into Database and create student mark sheet – Part 2

mutiple

My previous tutorial, related to Laravel Multiple Data Insert Into Database and create student mark sheet – Part 1! you have learned how to insert multiple data in laravel.

After understanding my previous tutorial, You have to change or insert new student marks on your list so you have to follow on this tutorial.

In this tutorial, you have just followed the previous tutorial, But you have some changes in your Controller File and blade file.


Open the Url:


Open Edit Page:


After Edit & Insert New data:


Step 1: Changes in StudentController file

After opening the Controller file, we have to create two methods.

  • edit => This method uses to get the data from the database to change.
  • update => This method uses to change the data.

After understanding the methods, you have to open your text editor and put the below code.

    public function edit($id){
        $rowReplace = 0;
        $sub_student = DB::table('student_sub')->where('student_id','=',$id)->get();
        $student = Student::find($id);  
        return view('Admin/student/edit',compact('student','sub_student','rowReplace'));
    }
    public function update(Request $request, $id){
        $this->validate($request,[
            'student_name' => 'required|max:255',
            'student_std' => 'required|max:255',
            'row.*.subject' => 'required|max:255',
            'row.*.total_marks' => 'required|max:255',
            'row.*.obtain_marks' => 'required|max:255',
            'row.*.status' => 'required|max:255',
        ],[
            'student_name.required' => 'Student Name is required.',
            'student_std.required' => 'Standard is required.',
            'row.*.subject.required' => 'Subject is required.',
            'row.*.total_marks.required' => 'Total Marks is required.',
            'row.*.obtain_marks.required' => 'Obtain Marks is required.',
            'row.*.status.required' => 'Status is required.',
        ]);
        
        // MAIN STUDENT INFO UPDATED
        $form_data = array(
            'id' => $request->id,
            'student_name' => $request->student_name,
            'student_std' => $request->student_std,
        );
        Student::whereId($id)->update($form_data);
        
        // STUDENT MARK UPDATED
        $student_sub = $request->row;
        $update_array = [];
            foreach ($student_sub as $key => $value) {
                $update_array = $value;
                DB::table('student_sub')->where('id', '=',$key)->update($update_array);
            } 
            if (!empty($student_sub)) {   
                foreach ($student_sub as $key => $value) {
                    $update_array = $value;
                    $update_array['student_id'] = $request->id;
                }
                DB::table('student_sub')->where('id', '=',$key)->insert($update_array);
            }
        return redirect()->route('student');
    }

Step 2: Changes in the route file.

Open your route file and put the below code.

Route::get('student/edit/{id}', 'StudentController@edit')->name('student/edit');
Route::post('student/edit/{id}', 'StudentController@update')->name('student/edit');

Step 3: Changes and create a blade file.

In this step, we have to find resources/views and open the student folder. create a new file name edit.blade.php & changes in also index.blade.file.

Now, you have had to changes in index.blade.php

@extends('layouts.app') 
@section('content')
<div class="container" style="margin-top: 20px;">
    <div class="row justify-content-center">
        <div class="col-lg-10 card-header">
            <div class="row">
                <div class="col-md-10">
                    <h6>Available Student</h6>
                </div>
                <div class="col-md-2 pull-right">
                    <a class="btn btn-success" href="{{ route('student/create') }}">
                        <div class="text-right">Add New Student</div>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <br/>
    <div class="row justify-content-center ">
        <div class="col-lg-10 card">
            <table class="table mb-0">
                    <thead class="bg-light">
                        <th>#</th>
                        <th>Name</th>
                        <th>Standard</th>
                    </thead>
                    <tbody>
                        @foreach($showData as $key=>$students)
                                <tr>
                                    <td>{{ $key + 1 }}</td>
                                    <td>{{ $students->student_name }}</td>
                                    <td>{{ $students->student_std }}</td>
                                    <td class="buttons">
                                        <a href="{{ route('student/edit',$students->id) }}" class="btn btn-primary" style="">Edit Student</a>
                                    </td>
                                </tr>
                        @endforeach
                    </tbody>
            </table>
        </div>
    </div>
</div>
<style type="text/css">
    .card-header {
        border-radius: .625rem !important;
        box-shadow: 0 0.46875rem 2.1875rem rgba(90,97,105,.1), 
                    0 0.9375rem 1.40625rem rgba(90,97,105,.1), 
                    0 0.25rem 0.53125rem rgba(90,97,105,.12), 
                    0 0.125rem 0.1875rem rgba(90,97,105,.1);
    }
</style>
@endsection

Now, you have had to create edit.blade.php and put the below code.

@extends('layouts.app')
@section('content')
<div class="container" style="margin-top: 20px;">
    <div class="row justify-content-center">
        <div class="col-lg-10 card-header">
            <div class="row">
                <div class="col-md-10">
                    <h6>Create New Marksheet</h6>
                </div>
                <div class="col-md-2 pull-right">
                    <a class="btn btn-success" href="{{ route('student') }}">
                        <div class="text-right">Back</div>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <br/>
    <div class="container">
        @if(Session::has('success'))
            <div class="alert alert-success">
                {{Session::get('success')}}
            </div>
        @endif
        <form action="{{ route('student/edit',$student->id) }}" method="POST">
                        {{csrf_field() }}
            <section>
                <div class="form-group {{ $errors->has('student_name') ? 'has-error' : '' }}">
                    @csrf
                    <label class="label">Student Name:</label>
                    <input type="text" name="student_name" class="form-control student_name" value="{{ $student->student_name }}" />
                    <span class="text-danger">{{ $errors->first('student_name') }}</span>
                </div>
                    <div class="form-group {{ $errors->has('student_std') ? 'has-error' : '' }}">
                        <label class="label">Standard:</label>
                        <input type="text" name="student_std" class="form-control" value="{{ $student->student_std }}"/>
                        <span class="text-danger">{{ $errors->first('student_std') }}</span>
                    </div>
                <div class="panel panel-footer">
                    <table class="table table-bordered" id="crud_table">
                        <thead>
                            <tr>
                                <th>Subject</th>
                                <th>Total Marks</th>
                                <th>Obtain Marks</th>
                                <th>Status</th>
                                <th>
                                    <a href="#" class="btn btn-primary addRow">
                                        <i class="material-icons">add</i>
                                    </a>
                                </th>
                            </tr>
                        </thead>
                                @if(old('row')!= '')
                                    <tbody class="validation-tbody-destination" id="validation-tbody-destination">
                                        <?php 
                                        $old_row = old('row');
                                        $rowReplace = count($old_row);
                                        ?>
                                        @foreach($old_row as $key=>$value)
                                            <tr class="num-row main_data validation" id="num-row">
                                                <td>
                                                    <div class="form-group {{ $errors->has("row.$key.subject") ? 'has-error' : '' }}">
                                                        <input type="text" name="row[{{$key}}][subject]" class="form-control subject" id="subject" value="{{ $value['subject'] }}">
                                                        <span class="text-danger">{{ $errors->first("row.$key.subject") }}</span>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="form-group {{ $errors->has("row.$key.total_marks") ? 'has-error' : '' }}">
                                                        <input type="text" name="row[{{$key}}][total_marks]" class="form-control total_marks" id="total_marks" value="{{ $value['total_marks'] }}">
                                                        <span class="text-danger">{{ $errors->first("row.$key.total_marks") }}</span>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="form-group {{ $errors->has("row.$key.obtain_marks") ? 'has-error' : '' }}">
                                                        <input type="text" name="row[{{$key}}][obtain_marks]" class="form-control obtain_marks" id="obtain_marks" value="{{ $value['obtain_marks'] }}">
                                                        <span class="text-danger">{{ $errors->first("row.$key.obtain_marks") }}</span>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="form-group {{ $errors->has("row.$key.status") ? 'has-error' : '' }}">
                                                        <input type="text" name="row[{{$key}}][status]" class="form-control status" id="status" value="{{ $value['status'] }}">
                                                        <span class="text-danger">{{ $errors->first("row.$key.status") }}</span>
                                                    </div>
                                                </td>
                                                <td><a href="#" class="btn btn-danger remove"><i class="material-icons">remove</i></a></td>
                                            </tr>
                                        @endforeach 
                                    </tbody>
                                @else
                                    @if($sub_student != '')
                                        <?php $rowReplace = count($sub_student); ?>
                                            <tbody class="original-tbody-destination" id="original-tbody-destination">
                                                @foreach($sub_student as $key => $sub_students)
                                                    <tr class="table_field main_data " id="table_field">
                                                        <td>
                                                            <input type="text" name="row[{{$sub_students->id}}][subject]" class="form-control subject" id="subject" value="{{ $sub_students->subject }}">
                                                        </td>
                                                        <td>
                                                            <input type="text" name="row[{{$sub_students->id}}][total_marks]" class="form-control total_marks"  maxlength="3" id="total_marks" value="{{ $sub_students->total_marks }}">
                                                        </td>
                                                        <td>
                                                            <input type="text" name="row[{{$sub_students->id}}][obtain_marks]" class="form-control obtain_marks"  maxlength="3" id="obtain_marks" value="{{ $sub_students->obtain_marks }}">
                                                        </td>
                                                        <td>
                                                            <input type="text" name="row[{{$sub_students->id}}][status]" class="form-control status" id="status" value="{{ $sub_students->status }}">
                                                        </td>
                                                        <td><a href="#" class="btn btn-danger remove"><i class="material-icons">remove</i></a></td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                    @endif
                                @endif
                        <tfoot>
                            <tr>
                                <td></td>
                                <td>Total:<b class="total" id="total"></b> </td>
                                <td>Obtain:<b class="obtain" id="obtain"></b></td>
                                <td>Percentage:<b class="percentage" id="percentage"></b></td>
                                <td><input type="submit" value="Submit" class="btn btn-success submit" id="submit"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </section>
        </form>
    </div>
</div>
<style type="text/css">
    .card-header {
        border-radius: .625rem !important;
        box-shadow: 0 0.46875rem 2.1875rem rgba(90,97,105,.1), 
                    0 0.9375rem 1.40625rem rgba(90,97,105,.1), 
                    0 0.25rem 0.53125rem rgba(90,97,105,.12), 
                    0 0.125rem 0.1875rem rgba(90,97,105,.1);
    }
</style>
@endsection
@section('script')
<script type="text/javascript">
    $('tbody .main_data').delegate('.subject,.total_marks,.obtain_marks,.status','keyup',function(){
        var tr = $(this).parent().parent();
        var subject=tr.find('.subject').val();
        var total_marks=tr.find('.total_marks').val();
        var obtain_marks=tr.find('.obtain_marks').val();
        var status=tr.find('.status').val();
    });
    var int = "{{ $sub_students->id + 1 }}"; 
    function addRow(){
            var tr='<tr class="table_field main_data " id="table_field">'+
                '<td><input type="text" name="row['+ (int) +'][subject]" class="form-control subject" id="subject"></td>'+
                '<td><input type="text" name="row['+ (int) +'][total_marks]" class="form-control total_marks"  maxlength="3" id="total_marks"></td>'+
                '<td><input type="text" name="row['+ (int) +'][obtain_marks]" class="form-control obtain_marks"  maxlength="3" id="obtain_marks"></td>'+
                '<td><input type="text" name="row['+ (int) +'][status]" class="form-control status"  maxlength="3" id="status"></td>'+
                '<td><a href="#" class="btn btn-danger remove"><i class="material-icons">remove</i></a></td>'+
                '</tr>';
            $('.original-tbody-destination').append(tr);
            int++;
    };
    $('.addRow').on('click',function(){
        addRow();
    });
    $(document).on("keypress keyup blur",'.total_marks',function (event) {    
        $(this).val($(this).val().replace(/[^\d].+/, ""));
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });
    $('.subject').bind('keyup blur',function(){ 
        var node = $(this);
        node.val(node.val().replace(/[^a-zA-Z]/g,'') ); 
    });
    $('.student_name').bind('keyup blur',function(){ 
        var node = $(this);
        node.val(node.val().replace(/[^a-zA-Z ]/g,'') );
    });
    $(document).on("keypress keyup blur",'.obtain_marks',function (event) {    
        $(this).val($(this).val().replace(/[^\d].+/, ""));
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });
    $(document).ready(function () {
        $(".original-tbody-destination").on('input', '.total_marks', function () {
                var calculated_total_sum = 0;
                $(".original-tbody-destination .total_marks").each(function () {
                    var get_textbox_value = $(this).val();
                        if($.isNumeric(get_textbox_value)) {
                            calculated_total_sum += parseFloat(get_textbox_value);
                        }                 
                });
        $("#total").html(calculated_total_sum);
        });
    });
    $(document).ready(function () {
        $(".validation-tbody-destination").on('input', '.total_marks', function () {
                var calculated_total_sum = 0;
                $(".validation-tbody-destination .total_marks").each(function () {
                    var get_textbox_value = $(this).val();
                        if($.isNumeric(get_textbox_value)) {
                            calculated_total_sum += parseFloat(get_textbox_value);
                        }                 
                });
        $("#total").html(calculated_total_sum);
        });
    });
    $(document).ready(function () {
        $(".original-tbody-destination").on('input','.obtain_marks', function () {
            var calculated_total_sum = 0;
            $(".original-tbody-destination .obtain_marks").each(function () {
                var get_textbox_value = $(this).val();
                if($.isNumeric(get_textbox_value)) {
                    calculated_total_sum += parseFloat(get_textbox_value);
                }                  
            });
        $("#obtain").html(calculated_total_sum);
        });
    });
    $(document).ready(function () {
        $(".validation-tbody-destination").on('input','.obtain_marks', function () {
            var calculated_total_sum = 0;
            $(".validation-tbody-destination .obtain_marks").each(function () {
                var get_textbox_value = $(this).val();
                if($.isNumeric(get_textbox_value)) {
                    calculated_total_sum += parseFloat(get_textbox_value);
                }                  
            });
        $("#obtain").html(calculated_total_sum);
        });
    });
    $(document).on('click', '.remove', function(){
        var delete_row = $(this).data(".table_field");
            $(this).parent().parent().remove();
            $(".total_marks").trigger("input");
            $(".obtain_marks").trigger("input");
        });
    $(document).on('input','.total_marks', function(){
        var total = $(this).data(".total_marks",true);
            if($(this).val() > 100 ){
                alert('Enter a Marks 100');
            $(this).val('');
            $('#total').html('');
            }
    });
    $(document).on('input','.obtain_marks','.total_marks', function(){
        var obtain = $(this).data(".obtain_marks",true);
        if($(this).val() >= 33 && $(this).val() <= 100){
            $(this).parent().next().find(".status").prop("readonly", true).val("Pass");
        }else{
            $(this).parent().next().find(".status").prop("readonly", true).val("Fail");
        }
        var obtain = $(this).data(".obtain_marks",true);
        if ($(this).val() > 100){
            $(this).parent().next().find(".status").prop("readonly", true).val('Invalid Marks');
            alert('Enter a Marks below 100');
            $('#obtain').html('');
            $(this).val('');
        }
        var total = parseFloat($('#total').html());
        var obtain = parseFloat($('#obtain').html());
        $('#percentage').html((obtain * 100) / total);
    });
</script>
@endsection

Now we are ready to run our task with laravel , so run bellow command for the run:

php artisan serve

Now you have to open your browser and put below URL:

http://localhost:8000/student/

About Dhaval Shah

My name is Dhaval Shah. I'm a PHP developer, entrepreneur and CEO of DAG inventions PVT ltd. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress and Bootstrap.
Follow me on Github / Linkedin

Leave a Reply

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

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!