Database Setup and Model Creation – Laravel Tutorial Part 3
Welcome back to our ongoing Laravel tutorial series! In Part 2, we learned how to define routes, create controllers, and build views for our website. Now, in Part 3, we’ll delve into setting up a database and creating models in Laravel. By the end of this tutorial, you’ll have a solid understanding of Laravel’s database capabilities and how to interact with databases using Eloquent ORM.
Tutorial Part 3: Database Setup and Model Creation
Step 1: Configure Database Connection
- Open the
.env
file in your Laravel project root directory. - Update the database configuration variables according to your database setup. For example:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Step 2: Create Database Tables
- Laravel provides a powerful migration system for managing database schema changes. Run the following command to create a new migration file:
php artisan make:migration create_posts_table
- Open the newly created migration file in the
database/migrations
directory. - Define the schema for your
posts
table in theup
method. For example:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
- Run the migration to create the
posts
table in your database:
php artisan migrate
Step 3: Create Models
- Run the following command to generate a new model named
Post
:
php artisan make:model Post
- This command will create a new model file in the
app
directory.
Step 4: Define Model Relationships (Optional)
- If your application requires relationships between models, you can define them in your model classes. For example, if you have a
User
model and want to establish a one-to-many relationship with thePost
model:
class User extends Authenticatable
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
Conclusion: In Part 3 of our Laravel tutorial series, we’ve learned how to set up a database, create database tables using migrations, and generate models in Laravel. We’re now equipped to interact with the database using Eloquent ORM, Laravel’s built-in ActiveRecord implementation. In the next part of the series, we’ll dive deeper into CRUD (Create, Read, Update, Delete) operations and learn how to create, retrieve, update, and delete data from our database. Stay tuned for Part 4!