Step 1: Installing Laravel To begin, we need to install Laravel on our machine. If you are using Composer, the PHP package manager, you can easily do this by running the following command:
composer create-project --prefer-dist laravel/laravel rest-api
This command will install a fresh Laravel project in a directory named rest-api
.
Step 2: Database Setup Next, we need to setup our database. Laravel supports a variety of databases including MySQL, SQLite, PostgreSQL and SQL Server. For the purpose of this tutorial, we will be using MySQL.
To connect Laravel to MySQL, we need to
In your .env
file at the project's root, fill your database connection details like so:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
Remember to replace your_database_name
, your_username
and your_password
with your actual MySQL database details.
Step 3: Creating a Model and Migration
Now, let us create a model and a corresponding database table for our REST API. For purposes of this demonstration, we will create a Post
model. Laravel's artisan command makes this easy:
php artisan make:model Post -m
The -m
flag here generates a corresponding migration file for our Post model. You can think of a migration as a version control for your database.
This command will generate two new files: app/Post.php
for the model, and a migration file under database/migrations/
.
You can define the structure of the posts table in the migration file. A simple example to add title
and content
fields could be as follows:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Step 4: Migrating the Database Once we have defined our posts table, we can apply the migration to create the corresponding table in our database using the following command:
php artisan migrate
At this point, we have successfully set up a Laravel project, connected it to a MySQL database, and created our first model with its corresponding table. In the follow-up post, we will dive into creating routes and controllers for our Post
model. Stay tuned! 🚀
For more reading and learning on Laravel, I would highly recommend the official Laravel documentation. It's one of the most well documented resources out there.
Please note technology evolves quickly and you might find some parts of the documentation are outdated but it will still provide you with a good understanding of Laravel. 🔮