Create a Table
Laravel provide a simple way to create mysql table. For example, below is a sample of creating a user table.
Step 1: Create Migration
Run the following Artisan command to generate a migration file for creating the users
table:
php artisan make:migration create_users_table
Step 2: Define Table Schema
Open the newly created migration file (YYYY_MM_DD_create_users_table.php
) located in the database/migrations
directory. Define the table schema in the up
method using the Schema facade.
Example Migration
To create a users
table with the following columns:
id
: Auto-incrementing primary key for uniquely identifying each user.name
: String column to store the user's name.email
: Unique string column to store the user's email address.email_verified_at
: Nullable timestamp column to store the timestamp when the user's email was verified.password
: String column to store the user's password (hashed for security).remember_token
: String column to store the "remember me" token.created_at
andupdated_at
: Timestamp columns to automatically store the creation and last update timestamps.
You should define your migration file as follows:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
Step 3: Run Migration
Execute the migration to create the users
table in your database by running the following Artisan command:
php artisan migrate
or you can just migrate the table u want with
php artisan migrate --path=/database/migrations/2024_02_20_160511_create_users_table.php
Last updated