How To Insert Data To Database With Example In Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

How to Insert Data Into Table In Laravel

To Insert data from table we use SQL Insert statement

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);

To learn more about SQL, please visit our BajarangiSoft site.

How to insert data into database in laravel
Let's see


1.Create table  in database.
The query builder also provides an insert method for inserting records into the database table. The insert method accepts an array of column names and values:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this

class UserController extends Controller
{
    public function update(Request $request)
    {
        $user = DB::table('users')->insert(['first_name' => 'kiran', 'last_name' => 'v']);//inserting data 

        return 'Data inserted successfully';
    }
}
?>


You may even insert several records into the table with a single call to insert by passing an array of arrays. Each array represents a row to be inserted into the table:

DB::table('users')->insert([
['first_name' => 'shiva', 'last_name' => 'B'],
['first_name' => 'rajesh', 'last_name' => 'H'],
]);


The insertOrIgnore method will ignore duplicate record errors while inserting records into the database:

DB::table('users')->insertOrIgnore([
['id' => 1, 'email' => 'kiran@example.com'],
['id' => 2, 'email' => 'shiva@example.com'],
]);


Auto-Incrementing IDs: If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

$id = DB::table('users')->insertGetId(
['email' => 'kiran@example.com', 'votes' => 0]
);

Related Post