Home Backend Development PHP Tutorial Creating a Mini Blog API with Lithe and Eloquent

Creating a Mini Blog API with Lithe and Eloquent

Nov 30, 2024 am 10:08 AM

Criando uma API de Mini Blog com Lithe e Eloquent

In this tutorial, we will create a Mini Blog API using Lithe, a PHP framework that is simple and flexible, and Eloquent ORM, which facilitates interaction with the database. Lithe already configures Eloquent automatically, so the work we need to do is simple: adjust the environment variables and create the model and migration for our data.

Let's follow a simple step-by-step guide to build this API efficiently and without complications.


Step 1: Install Lithe

The first step is to install Lithe in your project. If you haven't done this yet, just run the following command in the terminal:

composer create-project lithephp/lithephp mini-blog-api
Copy after login
Copy after login

This command creates a new project using Lithe. Lithe already configures Eloquent for you automatically, but we need to adjust some settings in the .env file to connect to the database.


Step 2: Configure the Database

Now, let's configure the database. Open the .env file in the root of your project and edit the database settings. To use Eloquent ORM with MySQL, the settings should be like this:

DB_CONNECTION_METHOD=eloquent
DB_CONNECTION=mysql
DB_HOST=localhost
DB_NAME=lithe_eloquent
DB_USERNAME=root
DB_PASSWORD=
DB_SHOULD_INITIATE=true
Copy after login
Copy after login

Now, since Lithe already automatically configures Eloquent, the next step is to ensure that Eloquent ORM is installed. If you haven't already done so, run the command below to install Eloquent ORM:

composer require illuminate/database
Copy after login
Copy after login

After installation, Lithe will be ready to use Eloquent ORM and interact with the database. With this, the database is correctly configured for our Mini Blog!

API

Step 3: Create the Template and Migrate to Posts

Now, let's create the model and migration that will define the posts table in our database.

First, create the Post template with the command:

php line make:model Post
Copy after login
Copy after login

Then, create the migration for the posts table:

php line make:migration create_posts_table
Copy after login
Copy after login

The model and migration have already been created, now let's configure them.

Post Template

The Post model is located in src/models/Post.php. Edit the file like this:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // A tabela associada ao modelo
    protected $table = 'posts';

    // Campos que podem ser preenchidos via mass-assignment
    protected $fillable = ['title', 'content'];

    // Usar timestamps para created_at e updated_at
    public $timestamps = true;
}
Copy after login
Copy after login

In this code, we are defining the title and content fields as fillable, meaning they can be filled automatically when we create or update a post.

Posts Table Migration

The generated migration will be in src/database/migrations/{timestamp}_create_posts_table.php. Edit the migration to create the posts table structure:

composer create-project lithephp/lithephp mini-blog-api
Copy after login
Copy after login

Here, we are creating the posts table with the fields id, title, content, and the date and time fields created_at and updated_at.


Step 4: Run the Migration

With the migration and model ready, let's run the migration to create the posts table in the database. Run the following command:

DB_CONNECTION_METHOD=eloquent
DB_CONNECTION=mysql
DB_HOST=localhost
DB_NAME=lithe_eloquent
DB_USERNAME=root
DB_PASSWORD=
DB_SHOULD_INITIATE=true
Copy after login
Copy after login

This command will create the posts table in the database with the fields that we defined in the migration.


Step 5: Create the Controller for Posts

Now, let's create a controller to manage the API posts. The controller will be responsible for handling HTTP requests and returning data in an organized manner.

To create the controller, run:

composer require illuminate/database
Copy after login
Copy after login

This will generate a file at src/http/Controllers/PostController.php. Edit this file to include CRUD (create, read, update and delete) methods for posts.

Here is an example of what the PostController might look like:

php line make:model Post
Copy after login
Copy after login

Here, we have five basic methods:

  • index: Lists all posts.
  • show: Displays a specific post.
  • store: Create a new post.
  • update: Updates an existing post.
  • destroy: Deletes a post.

Step 6: Define API Routes

Now, let's define the routes for our posts API. Open the src/App.php file and add the following code:

php line make:migration create_posts_table
Copy after login
Copy after login

The code above creates an instance of the Lithe application. The line $app->set('routes', __DIR__ . '/routes'); tells Lithe where to find the route files. Lithe will automatically load all files into the src/routes folder. Each route file will be mapped to the URL based on its name. For example:

  • The cart.php file goes to the /cart route.
  • The admin/dashboard.php file goes to the /admin/dashboard route.

The $app->listen(); causes Lithe to start "listening" to requests, that is, it waits for requests and directs them to the defined routes.

Now, create a file called posts.php inside the src/routes/posts folder to represent the /posts route and add the following code:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // A tabela associada ao modelo
    protected $table = 'posts';

    // Campos que podem ser preenchidos via mass-assignment
    protected $fillable = ['title', 'content'];

    // Usar timestamps para created_at e updated_at
    public $timestamps = true;
}
Copy after login
Copy after login

These routes connect PostController methods to API URLs.


Step 7: Test the API

Now that everything is set up, you can test your API with tools like Postman or Insomnia. Here are the endpoints you can test:

  • GET /posts: Returns all posts.
  • GET /posts/:id: Returns a specific post.
  • POST /posts: Creates a new post.
  • PUT /posts/:id: Updates an existing post.
  • DELETE /posts/:id: Deletes a post.

Now, you've just created a Mini Blog API with Lithe and Eloquent ORM! Lithe automatically configured Eloquent for you, and we just made some modifications to the environment variables and created the necessary models and controllers. Now you have a complete RESTful API for managing blog posts.

For more information and details on how to use Lithe and Eloquent ORM, visit the official Lithe documentation here: Lithe Documentation.

The above is the detailed content of Creating a Mini Blog API with Lithe and Eloquent. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

See all articles