Here is how you create a table in a database in laravel 9. Before you start going through the steps, please make sure your connected to a database.
If you need some guidance on how to do so, here is a lession https://wecode101.com/how-to-connect-to-the-database-in-xampp-with-laravel-project .
Step 1. Create migration
Open a command line and go to the root of your project. Then execute command below:
php artisan make:migration create_posts_table
Step 2. Edit migration file
Go to directory database/migrations and you should see the migration file which should look something like this 2022_07_06_173818_create_posts_table.
You can now start editing the file as below:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->longText('title'); //this column was added
$table->longText('description'); //this column was added
$table->string('author'); //this column was added
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
};
In the class above you have an up method containing a schema with two columns id and timestamp that was created by default.
Now you can add columns to the schema. In this example, 3 more columns where added, title, description and author.
The title and description columns has the longText data type method which is the same as longtext in sql.
However, author has a string datatype method which is equivalent to varchar(255) in sql. The name of the columns are added to the methods as parameters and that is all you need to do in this step.
Step 3. Create table
Once you have finished adding your columns execute command below:
php artisan migrate
You should now see your table in the database.
Enjoy!