How to Build a Laravel 5.4 API: Project Creation, Database Setup, Model, Controller, and Routing
This guide demonstrates how to create a Laravel 5.4 API project, covering Composer project creation, database and users table setup, model and controller generation, route definition, and API testing, with complete code examples for each step.
This article explains how to develop an API using Laravel 5.4, starting with creating a new Laravel project via Composer.
composer create-project laravel/laravel=5.4.* laravel-api --prefer-distThe command uses create-project to generate a fresh Laravel installation, specifies the version constraint 5.4.*, sets the target directory laravel-api, and prefers downloading distribution packages for faster builds.
Next, a MySQL database is created and the .env file is updated with the new database credentials. If the .env file does not exist, copy .env.example to .env.
A users table is defined with the following SQL:
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT '用户名',
`phone` varchar(20) CHARACTER SET utf8 NOT NULL DEFAULT '' COMMENT '手机号码',
`created_at` timestamp NULL DEFAULT NULL COMMENT '创建时间',
`updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT='用户表';After the database is ready, generate an Eloquent model for the users table: php artisan make:model Models/User Then create a controller to handle API requests: php artisan make:controller UserController The generated app/Http/Controllers/UserController.php contains a method to retrieve a user by ID and return it as JSON:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller {
public function getUser($id) {
$user = User::find($id);
return response()->json($user);
}
}Define a route for the API in routes/api.php: Route::post('/user/{id}', 'UserController@getUser'); Finally, the API can be accessed by sending a POST request to the endpoint, for example: http://your-domain.com/api/user/1 This completes the step‑by‑step setup of a simple Laravel API, including project creation, database configuration, model and controller generation, routing, and testing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
