How to insert data in database in laravel 5.8 and above

By Super Admin | Jan 09, 2021 | Laravel
Share :

https://www.fundaofwebit.com/post/how-to-insert-data-into-database-in-laravel-5-8

How to insert data in database in laravel 5.8 and above


Step 1: Install your Laravel by issuing the Composer with the command called create-project command in your terminal:

$ composer create-project --prefer-dist laravel/laravel blog "5.8.*"


Step 2: Setup your database (DB) and set the credentials in your environment file (.env) in your installed laravel application.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database  #do not use this symbol Hash (#) in database
DB_USERNAME=your_username  #do not use this symbol Hash (#) in username
DB_PASSWORD=your_password  #do not use this symbol Hash (#) in password


Step 3: Go to your application and open the folder by following:

app/Providers/AppServiceProvider.php, open this file and add the below code, to set the defaultStringLength to skip the Error called: Specified key was too long error.

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}


Step 4: Now, we will create the migration to create a table named students in a laravel database with following command as follows:

$ php artisan make:migration create_students_table

After successfully table created. open the migration file in the following path: database/migrations/somedate2021_create_students_table.php and paste the 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('students'function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email');
            $table->string('phone');
            $table->timestamps();
        });
    }

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


Step 5: Once you are setup with your migration table as above, then lets migrate this table into database with following command:

$ php artisan migrate

your table will be migrated successfully into database after the above command.

Step 6: Now, we will create a Eloquent Model with the following command to manage or perform the database table operations.

$ php artisan make:model Student

after successful creation of model in the following path: app/Student.php open the file and follow as below:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $table = 'students'; //type the table name
    protected $fillable = ['first_name','last_name','email','phone'];
}


Step 7: Create a controller named StudentController.php with the following command:

$ php artisan make:controller StudentController

after successful creation of StudentController, open the following path: app/Http/Controller/StudentController.php and paste the below code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Student;

class StudentController extends Controller
{

    public function create()
    {
        return view('student.create');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'first_name'=>'required|max:120',
            'last_name'=>'required|max:120',
            'email'=>'required|email|unique:students',
            'phone'=>'required|min:10|max:12'
        ]);

        $student = new Student();
        $student->first_name = $request->input('first_name');
        $student->last_name = $request->input('last_name');
        $student->email = $request->input('email');
        $student->phone = $request->input('phone');
        $student->save();
        return redirect('/add-students')->with('status','Inserted Successfully.');
    }

}


Step 8: Create the routes to call the form and submit the form in the following path: routes/web.php as follow:

Route::get('/add-students','StudentController@create');
Route::post('/store-students','StudentController@store');


Step 9: Now, lets create a student form in the following path as: resources/views/student/create.blade.php and paste the below form:

@extends('layouts.app')

@section('content')

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5>Add Student</h5>
                </div>
                <div class="card-body">

                    @if(session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status'}}
                        </div>
                    @endif

                    <form action="{{ url('store-students') }}" method="POST">
                        @csrf

                        <div class="form-group">
                            <label for="">First Name</label>
                            <input type="text" name="first_name" class="form-control" placeholder="Enter First Name">
                            @if($errors->has('first_name'))
                                <div class="error">{{ $errors->first('first_name'}}</div>
                            @endif
                        </div>

                        <div class="form-group">
                            <label for="">Last Name</label>
                            <input type="text" name="last_name" class="form-control" placeholder="Enter Last Name">
                            @if($errors->has('last_name'))
                                <div class="error">{{ $errors->first('last_name'}}</div>
                            @endif
                        </div>

                        <div class="form-group">
                            <label for="">Email Address</label>
                            <input type="text" name="email" class="form-control" placeholder="Enter Email Id">
                            @if($errors->has('email'))
                                <div class="error">{{ $errors->first('email'}}</div>
                            @endif
                        </div>

                        <div class="form-group">
                            <label for="">Phone Number</label>
                            <input type="text" name="phone" class="form-control" placeholder="Enter Phone Number">
                            @if($errors->has('phone'))
                                <div class="error">{{ $errors->first('phone'}}</div>
                            @endif
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">Save</button>
                        </div>
                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

@endsection


Thanks for reading...

https://www.fundaofwebit.com/post/how-to-insert-data-into-database-in-laravel-5-8

Share this blog on social platforms