You are currently viewing Several ways to insert data into a database table in Laravel

Several ways to insert data into a database table in Laravel

  • Post author:
  • Post category:Technology

In Laravel, a new record is added to the database using the create method. It is an Eloquent model method that accepts an array of data as its parameter. The information should line up with the columns in the database table that the model is linked to. Here is an illustration of how to insert a new record using the create method into a “users” table:

use App\User;

$user = User::create([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => Hash::make('password')
]);

In this illustration, an array of data is supplied to the create method on the User model when it is called. The fields in the “users” database’s “users” table correspond to the data in the array. The new model instance is returned together with a new record that was created using the supplied data by the create method.

You can specify which characteristics can be assigned in bulk by using the create method with mass assignments.

class User extends Model
{
    protected $fillable = [
        'name', 'email', 'password',
    ];
}

$user = User::create([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => Hash::make('password')
]);

In this case, you limit the characteristics that can be assigned in bulk to name, email, and password. This stops malicious users from modifying attributes that shouldn’t be modified.

There are a few other methods you may use in Laravel besides the create function to insert data into a database table. Here are a few examples:

Using the save method: To add a new record to the database, you can build a new model instance, set its attributes, and then execute the save method on it. For example:

$user = new User;
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->password = Hash::make('password');
$user->save();

Using the insert method: To add a new record to a table, use the insert method on the DB facade. The first argument for the insert method is an array of data, and the second argument is the name of the table. For example:

DB::table('users')->insert([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => Hash::make('password')
]);

Using the create and saveMany method on the model: This approach allows you to create numerous records at once. For example:

$users = [
    [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'password' => Hash::make('password')
    ],
    [
        'name' => 'Jane Doe',
        'email' => '[email protected]',
        'password' => Hash::make('password')
    ],
];

User::saveMany($users);

Using the firstOrCreate method: If a matching record is not already in the database, you may use the firstOrCreate method to add a new record. If a record doesn’t already exist, it will insert a new one after checking the current ones against the specified criteria. For example:

$user = User::firstOrCreate(
    ['email' => '[email protected]'],
    ['name' => 'John Doe', 'password' => Hash::make('password')]
);

Using the updateOrCreate method: Like the firstOrCreate method, updateOrCreate checks the existing records in accordance with the conditions provided; if they exist, they are updated; if not, a new record is inserted. For example:

$user = User::updateOrCreate(
    ['email' => '[email protected]'],
    ['name' => 'John Doe', 'password' => Hash::make('password')]
);

Using Eloquent events: When a record is added or changed, you may use Eloquent events to carry out extra tasks. For instance, you can take action before and after a new record is inserted using the creating and created events.

class User extends Model
{
    protected $fillable = [
        'name', 'email', 'password',
    ];
    public static function boot()
    {
        parent::boot();

        static::creating(function ($user) {
            // before creating logic
        });

        static::created(function ($user) {
            // after creating logic
        });
    }
}

Using Query Builder: You can use the query builder in Laravel to insert new records into a table.

$id = DB::table('users')->insertGetId(
    ['name' => 'John Doe', 'email' => '[email protected]','password' => Hash::make('password')]
);

This method will insert the data into the table and return the id of the inserted record.

Using Eloquent’s newQuery method : You can use newQuery method to insert data into a table.

$user = new User;
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->password = Hash::make('password');
$user->newQuery()->insert($user->attributesToArray());

When you need to insert a record utilizing a certain connection or you want to utilize a different insert technique, this method can be helpful.