LARAVEL Tutorial


Laravel 6 Insert Data From Database


In the previous tutorial, you have learned about laravel topics like laravel installation, configuration, form, validation, middleware, cookies. 

In this insert data into database table laravel tutorial. You will learn how to insert form data into a database table in laravel web applications.

Laravel Insert Data In Database Example

  • Install Laravel Application
  • Configure Database Detail
  • Create Model and Migration
  • Run Migration
  • Create Routes
  • Create Controller
  • Create Blade View
  • Start Development Server

Install Laravel Application

First of all, you need to download the laravel web application new setup. Please follow the given link to learn how to install a new application.

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_application_configuration
DB_USERNAME=root
DB_PASSWORD=root

Create Model and Migration

Next, we need to create a model and migration in your laravel web application using the php artisan make:model model_name -m. So run the following command in your project root directory.

Go to the command prompt

cd/project_root_directory

php artisan make:model Post -m

after that, go to database/migrations/ and find created migration file and add fields, as you want to in your database table.

Your migration file looks like:

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

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

And go to the app/ directory and find the model file.

Your model file looks like:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

Run Migration

Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :

..
use Illuminate\Support\Facades\Schema;
 
....
function boot()
{
    Schema::defaultStringLength(191);
}
... 

Next, go to command prompt and run the following command:

php artisan migrate
OR
php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

Route::get('show-form','PostController@showForm');
Route::post('insert-record','PostController@insertRecord');

Create Controller

Now, you need to create a controller file, so use the following command and create a new controller file:

php artisan make:controller controller_name

php artisan make:controller PostController

In this controller file, you need to write business logic to perform database operations:

After that, go to App/Http/Controllers/ directory and find the created PostController file and update the following code into your file:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response;
use App\Post;

class PostController extends Controller
{

    public function showForm()
    {
      return view('insert-form');
    }

    public function insertRecord(Request $request)
    {
        $data = request()->validate([
        'title' => 'required',
        'description' => 'required',
        ]);
       
        $check = Post::insert($data);
        return Redirect::to("show-form")->withSuccess('Great! Form successfully submit with validation.');
    }
}

Create Blade View

Next, you need to create a blade view file, so go resource/views and create a new file with insert-form.blade.php extension and update the following code into your file:

<html>
   <head>
      <title>Laravel Insert Form Data Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="csrf-token" content="{{ csrf_token() }}">
      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
   </head>
   <body>
      <div class="container mt-5">
         <div class="row">
            <div class="col-md-12">
 
               <form action="{{ url('insert-record') }}" method="post" accept-charset="utf-8">@csrf
                  <div class="form-group">
                     <label class="control-label col-sm-2" for="fname">Title</label>
                     <div class="col-sm-10">          
                        <input type="text" class="form-control" placeholder="Enter Title" name="title">
                        <span class="text-danger">{{ $errors->first('title') }}</span>
                     </div>
                  </div>
                  <div class="form-group">
                     <label class="control-label col-sm-2" for="comment">Description</label>
                     <div class="col-sm-10">
                        <textarea class="form-control" rows="5" name="description"></textarea>
                        <span class="text-danger">{{ $errors->first('description') }}</span>
                     </div>
                  </div>
                  <div class="form-group">
                     <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-success">Submit</button>
                     </div>
                  </div>
               </form>
            </div>
         </div>
      </div>
   </body>
</html>

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your browser and type the below-given URL into your browser:

http://localhost:8000/show-form

OR

http://localhost/project-name/public/show-form