How to insert a record into the Laravel table

Learn how to insert records into a Laravel table with an example.

Inserting a Record into a Laravel Table

Laravel is an increasingly popular open-source PHP framework for the development of web applications. It provides an expressive, elegant syntax for working with databases and writing powerful queries. In this tutorial, we'll learn how to insert a record into a Laravel table.

First, we'll need to create a migration to set up our database table. To do this, run the following command in the terminal:

php artisan make:migration create_table_name_table

This will create a migration file in the database/migrations directory. Open the file and add the schema for your table:

Schema::create('table_name', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email');
    $table->timestamps();
});

Now, you can run the migration with the following command:

php artisan migrate

Next, we need to create a model that will interact with our table. To do this, run the following command in the terminal:

php artisan make:model TableName

This will create a model file in the app directory. This model will be used to interact with our table. Open the model file and add the following code:

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

Now, we can create a record in our table. To do this, we can use the Eloquent create method. This method takes an array of attributes and creates a record in the database. For example:

TableName::create([
    'name' => 'John Doe',
    'email' => '[email protected]',
]);

This code will create a new record in the table with the specified attributes. You can also use Eloquent's save method to update an existing record. For example:

$tableName = TableName::find(1);
$tableName->name = 'Jane Doe';
$tableName->save();

This code will update the record with an id of 1 and set the name to 'Jane Doe'.

In summary, we have learned how to insert a record into a Laravel table. We have created a migration to set up our table, created a model to interact with our table, and used Eloquent's create and save methods to insert and update records.

Answers (0)