Insert Form Data Into Database Using Laravel | Save Form Submit

install laravel, laravel install mysql, laravel get all data records, insert form data into database using laravel, laravel crud example, laravel custom 404, laravel registration and login, laravel 5.7 email verification, laravel 5.8 crud, laravel email verification, laravel facebook login, laravel google login, laravel file upload, laravel image upload, laravel image upload validation, laravel file upload validation, laravel form validation, laravel one to one relationship

Learn how to Insert Form Data Into Database Using Laravel in this article.

We will create one form in this tutorial and we will save this form data into MySQL database.

A submit button will be used to insert or submit form data into database using laravel.

We will use MySQL database. Here you can read on installing MySQL database with laravel and sequel pro.

Web Host Recommendation

If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.

Click this link to see affordable plans.

(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)

Last view of tutorial

Below video shows what we will develop today.

Step 1. Create devices table

First of all create a new laravel project using below command.

laravel new allrecordform
  • It will create a new project named allrecordform.

Now create a new table using the following command

php artisan make:migration create_devices_table
  • After this command, you will find one migration file in database->migrations directory.

This file should contain the below source code

<?php
 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
 
class CreateDevicesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('devices', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('description');
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('devices');
    }
}

Inside Schema::create() method, I have added below two lines

$table->string('name');
$table->text('description');
  • These two lines will create two columns in table named “name” and “description.

Now run migrate command as per the below

php artisan migrate
  • After this, a new table named “devices” will be created in your database.

Step 2. Defining routes

You should have a file called web.php in routes directory.

Write down the below source code in this file.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/devices','DevicesController@index');

Route::get('/devices/create','DevicesController@create');

Route::post('/devicesaction','DevicesController@storeDevice');
  • I have defined three routes in this file. When you fire http://127.0.0.1:8000/devices in browser, system will trigger first route. It will call index() method in DevicesController.php file. (we will create this file later)
  • Similarly, other two routes will work according to their definition. (create() method and storeDevice() method for second and third route respectively)

Step 3. Creating a Model class

To use eloquent ORM while working with database, we need to have one model class for each table.

Here we have created a table named devices. A name of model class should be the singular form of tables’s name.

So our model’s name should be “Device.”

Run the below command to make Device model.

php artisan make:model Device
  • With the help of above command, System will generate new file Device.php in app directory. Source code for this model class is as the below
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Device extends Model
{
    //
}

Step 4. Generation of Controller Class

In route file (web.php) we have defined some routes which were referring to the DevicesController.php file

So let us create this controller file. Fire the below command

php artisan make:controller DevicesController
  • Now check your app->Http->Controllers directory. There should be a file  DevicesController.php file here.

Add the below code structure in DevicesController.php file

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Device;

class DevicesController extends Controller
{
    public function index(){

        $devices = Device::all();

        return view('devices.index',compact('devices'));
    }

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

    public function storeDevice(){

        $device = new Device();

        $device->name = request('name');
        $device->description = request('description');

        $device->save();

        return redirect('/devices');

    }

}

This file contains three methods which will decide the flow of our laravel project.

First of all, read the below code

 public function index(){

        $devices = Device::all();

        return view('devices.index',compact('devices'));
    }
  • index() method will first get all the data from “devices” table.
  • Compiler will store all these data into the variable called $devices.
  • Then it will return one view file (index.blade.php). A file is located in the resources->views->devices directory. (By default, we have only resources->views directory. Inside views, we will create devices folder later)
  • There is a second parameter in the return statement. ( compact’devices’ ). These will pass the variable $devices in view file called index.blade.php that we will create in next step.

Now attend the following code

public function create(){
        return view('devices.create');
    }
  • This method is very simple. It is just returning one view file called create.blade.php which we will also create in next step.

Now see the last method.

public function storeDevice(){

        $device = new Device();

        $device->name = request('name');
        $device->description = request('description');

        $device->save();

        return redirect('/devices');

    }
  • First of all, compiler will create a new variable $device with help of model class “Device.”
  • Compiler will run this method when the user clicks the “Submit” button on the form. Here, it will also get two parameters (name and description.) These two will contain the values entered by the user.
  • Then it will fetch the value of the parameter “name” and will store it in $device->name
  • $device->description will have the value of description parameter.
  • Finally, A line $device->save() will insert the form data into the devices table.
  • At last it will return a redirect call to /devices route.

Step 5. View files

Now final task is to create blade view files.

First of all, create a new folder named “devices” inside resources->views directory.

Inside this devices folder, make a new php file named index.blade.php

Code snippet for index.blade.php is as the below

</<!DOCTYPE html>
<html>
<head>
   
</head>
<body>

<h1>All Information About Devices</h1>

@foreach ($devices as $device)
<li> {{ $device}}  </li>
@endforeach

<h1>Only Names Of Devices</h1>

@foreach ($devices as $device)

<li> {{ $device->name}}  </li>

@endforeach

<h1>Only Description Of Devices</h1>

@foreach ($devices as $device)

<li> {{ $device->description}}  </li>

@endforeach

</body>
</html>
  • Above code contains three @foreach loops.
  • This file will show all the rows of the devices table using first @foreach loop.
  • Second loop will print only names of the devices and the last one will print desription of the device.

Now make a new file named create.blade.php in resources->views->devices directory.

Source for this create.blade.php is as the below

</<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
* {box-sizing: border-box;}

input[type=text], select, textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type=submit] {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

input[type=submit]:hover {
  background-color: #45a049;
}

.container {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
}
</style>
   
</head>
<body>

<h1>Create New Devices</h1>

<div class="container">

    <form method="POST" action="/devicesaction">

        {{ csrf_field() }}

       <div>
          <label >Device Name</label>
          <input type="text" name="name" placeholder="Device Name">

      </div>
      <div>
            <label >Device Description</label>
            <textarea name="description" placeholder="Device Description"></textarea>

      </div>
      <div>

            <input type="submit" value="Make Device">

      </div>

    </form>  

 </div>   

</body>
</html>
  • This view file is responsible for form creation. When user visits http://127.0.0.1:8000/devices/create url, compiler will execute above source code.
  • User will show one form which have two input fields : name and description.

See the below line

 <form method="POST" action="/devicesaction">
  • A method is post and action is /devicesaction. Means that when the user clicks the submit button, compiler will execute /devicesaction route in web.php file (see step 2.)
  • From here compiler will execute storeDevice() method from DevicesController.php file. (see step 4.)

After this much of coding, if you run your project, you should get the output as shown in youtube video at the starting of this article.

Web Host Recommendation

If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.

Click this link to see affordable plans.

(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)

Download Code for insert form data into database using laravel

https://github.com/1hardikparsania/Insert-Form-Data-Into-Database-Using-Laravel-Save-Form-Submit