How to insert data in database using Laravel framework

Today, We want to share with you insert form data into database using laravel.In this post we will show you insert form data into database using laravel 6, hear for laravel insert data into table without model we will give you demo and example for implement.In this post, we will learn about insert query in laravel with an example.

laravel insert data into table using model

There are the Following The simple About insert data in laravel 7 Full Information With Example and source code.

As I will cover this Post with live Working example to develop laravel insert query mysql, so the laravel db::query is used for this example is following below.

how to insert data in database using laravel framework PHP.

For insert data in MySQL using laravel first i have to make a table in data base.

here The INSERT INTO statement is used to insert create fresh new data to a MySQL table in data base:

INSERT INTO statement

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

To learn more about SQL, please visit our SQL tutorial.

For creating table the SQL query is:

Step 1: SQL Query

CREATE TABLE member_details

CREATE TABLE member_details
(
id int NOT NULL AUTO_INCREMENT,
profile_nm varchar(50),
real_nm varchar(50),
full_address varchar(50),
email varchar(50),
PRIMARY KEY (id)
);

Create 3 files for insert data in Laravel :

  • MemberInsertController.php (app/Http/Controllers/MemberInsertController.php)
  • Member_create.php (resources/views/Member_create.php)
  • web.php (routes/web.php)

Step 2: View File

Member_create.blade.php

<!DOCTYPE html>
<html>
<head>
<title>member Management | Add</title>
</head>
<body>
@if (session('status'))
<div class="alert alert-success" role="alert">
	<button type="button" class="close" data-dismiss="alert">×</button>
	{{ session('status') }}
</div>
@elseif(session('failed'))
<div class="alert alert-danger" role="alert">
	<button type="button" class="close" data-dismiss="alert">×</button>
	{{ session('failed') }}
</div>
@endif
<form action = "/create" method = "post">
	<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
	<table>
	<tr>
	<td>First Name</td>
	<td><input type='text' name='profile_nm' /></td>
	<tr>
	<td>Last Name</td>
	<td><input type="text" name='real_nm'/></td>
	</tr>
	<tr>
	<td>City Name</td>
	<td>
	<select name="full_address">
	<option value="bbsr">Bhubaneswar</option>
	<option value="cuttack">Cuttack</option>
	</select></td>
	</tr>
	<tr>
	<td>Email</td>
	<td><input type="text" name='email'/></td>
	</tr>

	<tr>
	<td colspan = '2'>
	<input type = 'submit' value = "Add member"/>
	</td>
	</tr>
	</table>
</form>
</body>
</html>

Step 3: Controller File

MemberInsertController.php

<?php
namespace App\Http\Controllers;
use App\MemberInsert;
use Illuminate\Http\Request;
use \Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class MemberInsertController extends Controller
{
    
    public function insert(){
        $urlData = getURLList();
        return view('Member_create');
    }
    public function create(Request $request){
        $rules = [
			'profile_nm' => 'required|string|min:3|max:255',
			'full_address' => 'required|string|min:3|max:255',
			'email' => 'required|string|email|max:255'
		];
		$validator = Validator::make($request->all(),$rules);
		if ($validator->fails()) {
			return redirect('insert')
			->withInput()
			->withErrors($validator);
		}
		else{
            $data = $request->input();
			try{
				$member = new MemberInsert;
                $member->profile_nm = $data['profile_nm'];
                $member->real_nm = $data['real_nm'];
				$member->full_address = $data['full_address'];
				$member->email = $data['email'];
				$member->save();
				return redirect('insert')->with('status',"Insert successfully");
			}
			catch(Exception $e){
				return redirect('insert')->with('failed',"operation failed");
			}
		}
    }
}

Step 4: Model File

MemberInsert.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class MemberInsert extends Model
{
	protected $table = 'member_details';
	public $timestamps = true;
	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = [
		'profile_nm', 'real_nm','full_address', 'email',
	];
}

Step 5: Routes File

web.php

<?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!
|
*/
//insert data
Route::get('insert','[email protected]');
Route::post('create','[email protected]');

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about insert form data into database using laravel.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Laravel 5.7 JQuery Form Validation Example Tutorial
  2.   Laravel Database Joins Query Builder
  3.   Laravel MySQL Advanced Query Techniques with Example
  4.   Laravel 6 try catch Database Transaction
  5.   PHP nested While Loops and Multiple Conditions
  6.   Laravel Combine two DB query results Example
  7.   Laravel Installer Create Web Application install scripts
  8.   Laravel Advance Database Query Builder
  9.   How to Solve Error call to a member function toArray() on null?
  10.   Advanced Laravel 5.7 Eloquent Queries Builder