This article brings you relevant knowledge about laravel, which mainly introduces issues related to the use of Swagger. Let’s take a look at generating swagger based on Laravel as an example. I hope it will be helpful to everyone. help.

[Related recommendations: laravel video tutorial]
swagger is too spicy?
This tutorial is based on Laravel generating swagger as an example. In fact, this thing is basically the same as a language or a framework, because they all use public json, and scan the "language" predetermined by swagger through the program. ”, the generated structure is stored in json and displayed through swagger ui (or developed by yourself).
For PHP developers, most students dislike swagger. Because this seems to be very troublesome to write. When I think about the code that can be written in PHP in minutes, it takes 10 minutes to write swagger, and I resist this thing in my heart.
Students who are involved in Java development know that most of them use swagger, because Java needs to maintain the data structure, and swagger is more flexible to integrate in Java.
At this time, if you see php in java saying that swagger is anti-human, it will be too troublesome. It is a product of ancient times. The Java friends around me will be secretly happy that they don’t use such useful things, and they also say that PHP is the best language in the world.
Why do I use swagger
I have been writing automatic code generation recently. In fact, Laravel now automatically generates CURD. For example, like laravel-admin, a command generates CURD, but after generation, the data looks very cold. For example, some fields do not need to be displayed, some need to be selected for associated enumerations, some are hasMany, and the overtrue (super) api scaffolding is also very good
Therefore, swaager can also write automated generation according to business needs
L5-Swagger
https://github.com/DarkaOnLine/L5-Swagger
Installation:
composer require "darkaonline/l5-swagger"
Use:
php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" php artisan l5-swagger:generate
Fill in the following example to generate and then access
/api/documentation
@OA\Info is required
Example
/** * @OA\Info( * version="1.0.0", * title="L5 OpenApi", * description="L5 Swagger OpenApi description", * @OA\Contact( * email="darius@matulionis.lt" * ), * @OA\License( * name="Apache 2.0", * url="http://www.apache.org/licenses/LICENSE-2.0.html" * ) * ) */
get request
If you want to match the value in path, then in path query in query
/**
* @OA\Get(
* path="/projects/{id}",
* operationId="getProjectById",
* tags={"Projects"},
* summary="Get project information",
* description="Returns project data",
* @OA\Parameter(
* name="id",
* description="Project id",
* required=true,
* in="path",
* @OA\Schema(
* type="integer"
* )
* ),
* @OA\Response(
* response=200,
* description="successful operation"
* ),
* @OA\Response(response=400, description="Bad request"),
* @OA\Response(response=404, description="Resource Not Found"),
* security={
* {
* "oauth2_security_example": {"write:projects", "read:projects"}
* }
* },
* )
*/
POST request
/**
* @OA\Post(
* path="/api/test/store",
* operationId="api/test/store",
* tags={"Test"},
* summary="Test创建",
* description="Test提交创建",
* @OA\Parameter(
* name="id",
* description="",
* required=false,
* in="query",
* ),
* @OA\Response(
* response=200,
* description="successful operation",
* @OA\JsonContent(
* ref="#/components/schemas/Test"
* )
* ),
* @OA\Response(response=400, description="Bad request"),
* @OA\Response(response=404, description="Resource Not Found"),
* security={
* {
* "api_key":{}
* }
* },
* )
*/
File upload parameters
* @OA\RequestBody( * @OA\MediaType( * mediaType="multipart/form-data", * @OA\Schema( * type="object", * @OA\Property( * property="file", * type="file", * ), * ), * ) * ),
Passed in as enumeration
* @OA\Parameter(
* name="status",
* in="query",
* description="状态",
* required=true,
* explode=true,
* @OA\Schema(
* type="array",
* default="available",
* @OA\Items(
* type="string",
* enum = {"available", "pending", "sold"},
* )
* )
* ),
Body is submitted in Json mode
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* @OA\Property(
* property="id",
* type="string"
* ),
* @OA\Property(
* property="name",
* type="string"
* ),
* example={"id": 10, "name": "Jessica Smith"}
* )
* )
* ),

Use structure Schema as request parameter
* @OA\RequestBody( * description="order placed for purchasing th pet", * required=true, * @OA\JsonContent(ref="#/components/schemas/UserModel") * ),
Usage of Schema
/**
* @OA\Schema(
* schema="UserModel",
* required={"username", "age"},
* @OA\Property(
* property="username",
* format="string",
* description="用户名称",
* example="小廖",
* ),
* @OA\Property(
* property="age",
* format="int",
* description="年龄",
* example=1,
* nullable=true,
* )
* )
*/
Enumeration
An enumeration creates a Schema separately
/**
* @OA\Schema(
* schema="product_status",
* type="string",
* description="The status of a product",
* enum={"available", "discontinued"},
* default="available"
* )
*/
Mapped to the model Specific fields
* @OA\Property( * property="status", * ref="#/components/schemas/product_status" * ),
So that front-end developers can
Associate the model
It is similar to the enumeration, through a Property association model
* @OA\Property( * property="user_detail", * ref="#/components/schemas/UserModel2" * ),
Associate the model and the enumeration For example, the requested parameters and parameters can be automatically generated, and the returned structure 
is returned to the model structure
* @OA\Response( * response=200, * description="successful operation", * @OA\JsonContent( * type="array", * @OA\Items(ref="#/components/schemas/UserModel"), * @OA\Items(ref="#/components/schemas/UserModel2") * ) * ),
Just like the day the front-end girl told you, brother, payment status What does 3 stand for? Maybe you can quickly tell it is a certain state, but if I ask you what state 11 is, people will be confused.
Through swagger's Schema, front-end personnel can understand the structural information of the back-end, such as:

Everyone, these can be programmed automatically and generated automatically, and the work efficiency is not required Too cool
Multiple merged Schemas
/**
* @OA\Schema(
* schema="UserModel",
* allOf={
* @OA\Schema(ref="#/components/schemas/UserModel2"),
* @OA\Schema(
* type="object",
* description="Represents an authenticated user",
* required={
* "email",
* "role",
* },
* additionalProperties=false,
* @OA\Property(
* property="email",
* type="string",
* example="user@example.com",
* nullable=true,
* ),
* )
* }
* )
*/
Verification provides two methods, outh2 and apikey, and is written in the global configuration (can also be in any directory)
/** * @OA\SecurityScheme( * type="apiKey", * in="query", * securityScheme="api_key", * name="api_key" * ) */
In Add
security={{"api_key": {}}},
to the interface. At this time, a lock-like thing will appear in the swagger Ui.

You can enter your own token, and the token will be brought when making a request.

It can be combined with Laravel's own token verification. You can refer to the previously written article Laravel guard Chrysanthemum Guardian
For more usage methods, you can view the official website examples: https:/ /github.com/zircote/swagger-php/tree/master/Examples/petstore-3.0
Possible problems
If the online environment cannot be accessed, It may be a problem with your nginx configuration, because laravel-swagger echoes the js output through file_content_get(). Judging from your nginx configuration, if it is a .js or css file, it is a static file, so index.php cannot be reached, and the file_content_get function cannot be executed. You can refer to nginx configuration:
charset utf-8;
client_max_body_size 128M;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass php74:9000 这个换成你自己的;
try_files $uri =404;
}
[Related recommendations: laravel video tutorial]
The above is the detailed content of Learn more about the use of Laravel Swagger. For more information, please follow other related articles on the PHP Chinese website!
Laravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AMLaravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.
Laravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AMThe Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.
Laravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AMThe comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.
Laravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AMHow does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.
Why is Laravel so popular?Apr 02, 2025 pm 02:16 PMLaravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.
Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AMBoth Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.
Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PMPHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.
Is Laravel a frontend or backend?Mar 27, 2025 pm 05:31 PMLaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)







