# database
# Create data table
As mentioned earlier in lifecycle hooks , you can create
data tables after the plugin is enabled. Schema Facade
is required to
create a data table , but you don't have to write
use Schema; in ``callbacks.php
or bootstrap.php
.
Data tables can be created by calling the
create static method on the ``Schema
Facade . The create
method
receives two parameters. The first parameter is the table name, you
don't need to manually add the data table prefix, because Laravel will
automatically add it for you. The second parameter is a callback
function, which contains a parameter of type
Illuminate\Database\Schema\Blueprint
.
The code to create the data table is roughly like this:
Schema::create( ' my_table ' , function ( $table ) {
// There are many instance methods on the $table parameter
}) ;
The definition of each column in the table is carried out by calling the
instance method on the $table
variable. Regarding how to define the
fields in the table, the Laravel
documentation (opens new window)
has a fairly detailed introduction, so I won't go into details here.
It is worth noting that before creating a data table, it is necessary to check whether the data table already exists:
if ( ! Schema::hasTable( ' my_table' )) {
Schema:: : create( ' my_table ' , function ( $table ) {}) ;
}
# through the DB
Facade
Laravel provides DB
Facade to allow you to operate the database. This
is a relatively low-level approach that requires you to have a certain
understanding of database operations. Read the Laravel
documentation (opens new window)
about DB
Facade .
# Operate the database through Eloquent ORM
You can also work with databases through the Eloquent ORM. If you are
relatively new to database operations, then you can choose to use this
approach. With Eloquent ORM, you don't need to manually operate the
database (of course, it is still necessary to create data tables through
Schema ), you only need to define the data model, and you can easily use the database. Read
the
Laravel documentation
for (opens new window) details .