Laravel Multiple Data Insert Into Database and create student mark sheet – Part 1

mutiple

Student Marksheet Details :


Student Marksheet Validation:


Student Marksheet Views:


Today, we share with you a very important tutorial on Laravel Multiple Data Insert Into Database. in these tutorials, we are using simple data insert with one student name & multiple subject insert. You can easily create a student mark sheet.so, here we are starting our first part of our Student Marksheet.

Overview:

In this tutorial, you will learn very basic multiple data insert with laravel. I am going to show you step by step so, it will better understand if you are new in laravel. So just follow listed steps:

Overview Of Task:

  • Step 1: Install Laravel latest version
  • Step 2: Database updation
  • Step 3: Create database tables
  • Step 4: Create a route
  • Step 5: Create Controller and Model
  • Step 6: Create Blade Files

Step 1: Install Laravel Latest Version

First of all, we need to get fresh version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel student

Step 2: Database updation

In the second step, we have to open .env file in the Laravel folder & changes of the database name, password, and username.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE= your database name(Example. student)
DB_USERNAME=your database username(Example. root)
DB_PASSWORD=your database password(Example. root)


Step 3: Create database tables

In this step, we create two database tables, so open your terminal and run this below command.

php artisan make:migration create_student_table
php artisan make:migration create_substudent_table

After these two commands perform you have to open {Project Name}/database/migration and put below code.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
       Schema::create('student', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('student_name');
            $table->string('student_std');
            $table->enum('deleted', [0 , 1])->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddSubStudentTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('substudent',function($table){
            $table->bigIncrements('id');
            $table->integer('student_id');
            $table->string('subject');
            $table->integer('total_marks');
            $table->integer('obtain_marks');
            $table->enum('status',['pass','fail'])->default('fail');
            $table->enum('deleted', [0 , 1])->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

Now you have to run this migration by the following command:

php artisan migrate

Step 4: Create a route

In this step, we have to find routes/web.php and put the below code.


Route::get('student', 'StudentController@index')->name('student');
Route::get('student/create', 'StudentController@create')->name('student/create');
Route::post('student/store', 'StudentController@store')->name('student/store');

Step 5:Create Controller and Model

In this step we have to create Controller & Model, so open your terminal and run below command.

php artisan make:controller StudentController --resource --model=Student

After this Command, we have to create three methods in laravel.
index method

  • index => This method used to show the student data.
  • create => This method used to create data.
  • store => This method uses for an entered data stores in the database.

In this step, we have to find app/Http/Controllers/StudentController.php and put the below code.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use Redirect,Response,DB,Config;
use App\Student;
use App\Http\Controllers\Controller;

class StudentController extends Controller
{
    public function index(){
        $showData = Student::latest()->get();
 	return view('student/index',compact('showData'));
    }
    public function create(){
        $rowReplace = 0;
        return view('student/create', compact("rowReplace"));
    }
    public function store(Request $request){
        $this->validate($request,[
            'student_name' => 'required|max:255|unique:students',
            '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.',
        ]);
        $storeData = new Student;
        $storeData = $storeData->storeData($request);
        return redirect()->route('student');
    }
}

In this step, we have to find app/Student.php and put the below code.

<?php

namespace App;
use Redirect,Response,DB,Config;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
 	protected $fillable = ['student_name','student_std','subject','total_marks','obtain_marks','status'];
    protected $guarded = [];
    protected $table = 'students';
    
    public function storeData($request){
    	$student = Student::create([
            'student_name'=>request('student_name'),
            'student_std'=>request('student_std')
        ]);
        $student_sub = $request->row;
        $insert_ary = [];
        foreach ($student_sub as $key => $value) {
            $insert_ary[$key] = $value;
            $insert_ary[$key]['student_id'] = $student->id;
        }
        DB::table('student_sub')->insert($insert_ary);
    }
}

Step 6: Create Blade Files

In this step, we have to find resources/views and create a new folder name student & put the below code.

You have to changes layouts in app.blade.php and create your sidebar and name it Student.

<html class="no-js h-100" lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Blog Expert</title>
        <meta name="description" content="A high-quality & free Bootstrap admin dashboard template pack that comes with lots of templates and components.">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
        <link rel="stylesheet" id="main-stylesheet" data-version="1.1.0" href="{{ asset('css/shards-dashboards.1.1.0.min.css') }}">
        <link rel="stylesheet" href="{{ asset('css/extras.1.1.0.min.css') }}">
    </head>
    <body class="h-100">
        <div class="container-fluid">
            <div class="row">
                <!-- Main Sidebar -->
                <aside class="main-sidebar col-12 col-md-3 col-lg-2 px-0">
                    <div class="main-navbar">
                        <nav class="navbar align-items-stretch navbar-light bg-white flex-md-nowrap border-bottom p-0">
                            <a class="navbar-brand w-100 mr-0" href="/home" style="line-height: 25px;">
                                <div class="d-table m-auto">
                                    <img id="main-logo" class="d-inline-block align-top mr-1" style="max-width: 25px;" src="{{ asset('images/shards-dashboards-logo.svg') }}" alt="Shards Dashboard">
                                    <span class="d-none d-md-inline ml-1">Dashboard</span>
                                </div>
                            </a>
                            <a class="toggle-sidebar d-sm-inline d-md-none d-lg-none">
                            <i class="material-icons"></i>
                            </a>
                        </nav>
                    </div>
                    <div class="nav-wrapper">
                        <ul class="nav flex-column">
                            <li class="nav-item">
                                <a class="nav-link " href="{{ route('student') }}">
                                <i class="material-icons">vertical_split</i>
                                <span>Student</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </aside>
                <!-- End Main Sidebar -->
                <main class="main-content col-lg-10 col-md-9 col-sm-12 p-0 offset-lg-2 offset-md-3">
                    <div class="main-navbar sticky-top bg-white">
                        <!-- Main Navbar -->
                        <nav class="navbar align-items-stretch navbar-light flex-md-nowrap p-0">
                            <form action="#" class="w-100">
                                <h4 class="text-center welcome" style="margin: 10px;
                                    font-size: 25px;">Welcome to Dashboard
                                </h4>
                            </form>
                            <ul class="navbar-nav border-left flex-row ">
                                <li class="nav-item dropdown">
                                    <a class="nav-link dropdown-toggle text-nowrap px-3" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
                                    <img class="user-avatar rounded-circle mr-2" src="{{ asset('images/avatars/0.jpg') }}" alt="User Avatar">
                                    <span class="d-none d-md-inline-block">
                                        @if(auth()->check())
                                        {{ Auth::User()->name }}
                                        @endif
                                    </span>
                                    </a>
                                    <div class="dropdown-menu dropdown-menu-small">
                                        @if(auth()->check())
                                        <a class="dropdown-item" href=" {{ route('view/Profile', [Auth::User()->id]) }}">
                                            @endif
                                        <i class="material-icons"></i> Profile</a>
                                        <a class="dropdown-item" href="{{ route('posts') }}">
                                        <i class="material-icons">vertical_split</i> Blog Posts</a>
                                        <a class="dropdown-item" href="{{ route('posts/create') }}">
                                        <i class="material-icons">note_add</i> Add New Post</a>
                                        <div class="dropdown-divider"></div>
                                        <a class="dropdown-item text-danger" href="{{ route('logout') }}">
                                        <i class="material-icons text-danger"></i> Logout </a>
                                    </div>
                                </li>
                            </ul>
                            <nav class="nav">
                                <a href="#" class="nav-link nav-link-icon toggle-sidebar d-md-inline d-lg-none text-center border-left" data-toggle="collapse" data-target=".header-navbar" aria-expanded="false" aria-controls="header-navbar">
                                <i class="material-icons"></i>
                                </a>
                            </nav>
                        </nav>
                    </div>
                    <div class="main-content-container container-fluid px-4">
                        @yield('content')
                    </div>
                </main>
            </div>
        </div>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
        <script src="https://unpkg.com/shards-ui@latest/dist/js/shards.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Sharrre/2.0.1/jquery.sharrre.min.js"></script>
        <script src="{{ asset('js/extras.1.1.0.min.js') }}"></script>
        <script src="{{ asset('js/shards-dashboards.1.1.0.min.js') }}"></script>
        <script src="{{ asset('js/app/app-blog-overview.1.1.0.js') }}"></script>
        @yield('script')
    </body>
</html>

Now, you have had to create 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>
                                </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 create.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>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/store') }}" 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="{{ old('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="{{ old('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
                                    <tbody class="original-tbody-destination" id="original-tbody-destination">
                                    </tbody>
                                @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 = "{{ $rowReplace }}"; 
    function addRow(){
            var tr='<tr class="table_field main_data " id="table_field-'+ (int) +'">'+
                '<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++;
    };
    $(function() {
        $('.addRow').trigger("click");
    });
    $('.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/

Link of Second part:

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

About Dhaval Shah

My name is Dhaval Shah. I'm a Laravel developer. 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

7 Comments

    1. Thanks for your positive feedback we will try our best … As we have a lot to share so please be updated next part will be uploaded soon.

Leave a Reply to Dhaval Shah Cancel 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!