How to do insert using DB table in Laravel

How to do insert using DB table in Laravel

In laravel you can insert data to a table in two ways, the first one and the most common is using a model, create a model for that table and then insert the data, the second way is using DB::table(), in this article i will show you how to insert to database table using DB::table().

To insert data using DB::table(), simply specify the table name and then run the insert() method, the insert method takes an array as parameter, you need to specify the field name on that table.

Insert using DB table
DB::table(TABLE_NAME)->insert(array());
Example:
DB::table('users')->insert(array('name' => 'hannah',
      'email' => 'hannah@gmail.com'));
DB::table('product')->insert(array('product_code' => 'FF123',
      'product_name' => 'lcd tv',
                                                'price' => 2500));

The benefit of using DB::table for inserting data is that you don't need to create the model first, as long as the table exist you can insert it, no need to create the model.

Insert using model
After creating a model for that particular table, you can do something like this to insert the data:
$new_user = new Users();
$new_user->name = 'hannah';
$new_user->email = 'hannah@gmail.com';
$new_user->save();

As you can see the code is much more cleaner and easier to understand when inserting data using a model in laravel.


EmoticonEmoticon